Python
2021-08-03 10:52:07 39 举报
AI智能生成
Python
作者其他创作
大纲/内容
注释
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : ${DATE} ${TIME}
# @Author : ${USER}
# @Email : 874591940@qq.com
# @desc : ...
pip
导出
pip freeze > requirements.txt
导入
pip install -r requirements.txt
设置源
C:/Users/xx
使用指定目录的pip
D:\Application\Python3.7\python.exe -m pip install xxx
安装到当前目录
pip install xx -t ./
打包
pyinstaller -F -w -i xxx.ico xx.py
D:\Application\Python3.7\Scripts\pyinstaller.exe -F xxx.py
ini
configparser
def get_config():
"""
读取配置文件
:return:
"""
config = {}
# 读取配置文件
cp = configparser.ConfigParser()
cp.read('./config.ini', encoding="utf-8")
for header in cp.sections():
if header not in config:
config[header] = {}
# 按照键值对形式保存
for key, value in cp.items(header):
try:
# 自动转为整型
config[header][key] = int(value)
except:
config[header][key] = value.strip()
return config
"""
读取配置文件
:return:
"""
config = {}
# 读取配置文件
cp = configparser.ConfigParser()
cp.read('./config.ini', encoding="utf-8")
for header in cp.sections():
if header not in config:
config[header] = {}
# 按照键值对形式保存
for key, value in cp.items(header):
try:
# 自动转为整型
config[header][key] = int(value)
except:
config[header][key] = value.strip()
return config
office
word
python-docx
import docx
doc = docx.Document('1.docx')
# 查看
for i, p in enumerate(doc.paragraphs):
print(str(i) + ": " + str(p.text))
# 修改
doc.paragraphs[7].text = '77777'
doc.save('2.docx')
doc = docx.Document('1.docx')
# 查看
for i, p in enumerate(doc.paragraphs):
print(str(i) + ": " + str(p.text))
# 修改
doc.paragraphs[7].text = '77777'
doc.save('2.docx')
docxtpl
from docxtpl import DocxTemplate
temp = DocxTemplate('1.docx')
info = {
'key1': 'value1',
}
temp.render(info)
temp.save('2.docx')
temp = DocxTemplate('1.docx')
info = {
'key1': 'value1',
}
temp.render(info)
temp.save('2.docx')
word里要有{{ key1 }}
pandoc
excel
xlrd
import xlrd
# 打开excel
excel = xlrd.open_workbook('1.xlsx')
# 切换到指定工作簿
sheet = excel.sheet_by_name(sheet_name)
# sheet = excel.sheet_by_index(0)
# 获取列数据
data = sheet.col_values(0)
excel = xlrd.open_workbook('1.xlsx')
# 切换到指定工作簿
sheet = excel.sheet_by_name(sheet_name)
# sheet = excel.sheet_by_index(0)
# 获取列数据
data = sheet.col_values(0)
读取
区域
行
sheet.row_values(row) # 从0开始
列
sheet.col_values(col) # 从0开始
单元格
sheet.cell_value(row, col) # 从0开始
openpyxl
import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
# 打开excel
excel = openpyxl.load_workbook('1.xlsx')
# 切换到指定工作簿
sheet = excel[sheet_name]
# 修改
sheet['A1'] = '111'
# 保存
sheet.save('2.xlsx')
excel = openpyxl.load_workbook('1.xlsx')
# 切换到指定工作簿
sheet = excel[sheet_name]
# 修改
sheet['A1'] = '111'
# 保存
sheet.save('2.xlsx')
添加行
sheet.append([...])
修改样式
import openpyxl
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
# 1.打开工作簿
wb = openpyxl.load_workbook('1.xlsx')
sheet = wb.active
def set_font():
"""
设置单元格字体样式
Font(
name=None, # 字体名,可以用字体名字的字符串
strike=None, # 删除线,True/False
color=None, # 文字颜色
size=None, # 字号
bold=None, # 加粗, True/False
italic=None, # 倾斜,Tue/False
underline=None # 下划线, 'singleAccounting', 'double', 'single', 'doubleAccounting'
)
:return:
"""
font1 = Font(
size=20,
italic=True,
color='ff0000',
bold=True,
)
sheet['A1'] = '11111'
sheet['A1'].font = font1
def set_fill_style():
"""
设置单元格填充样式
PatternFill(
# 设置填充样式: 'darkGrid', 'darkTrellis', 'darkHorizontal', 'darkGray', 'lightDown', 'lightGray', 'solid', 'lightGrid', 'gray125', 'lightHorizontal', 'lightTrellis', 'darkDown', 'mediumGray', 'gray0625', 'darkUp', 'darkVertical', 'lightVertical', 'lightUp'
fill_type=None,
# 设置填充颜色
start_color=None
)
:return:
"""
fill = PatternFill(
fill_type='solid',
start_color='ffff00'
)
sheet['A1'].fill = fill
def set_align_style():
"""
设置单元格对齐样式
Alignment(
horizontal='right', # 水平方向:center, left, right
vertical='top' # 垂直方向: center, top, bottom
)
:return:
"""
al = Alignment(
horizontal='center', # 水平方向:center, left, right
vertical='center' # 垂直方向: center, top, bottom
)
sheet['A1'].alignment = al
def set_border_style():
"""
设置边框样式
Side(
border_style='thin',
color='0000ff'
)
Border(left=None, right=None, top=None, bottom=None)
"""
side = Side(border_style='thin', color='0000ff')
bd = Border(left=side, right=side, top=side, bottom=side)
sheet['B2'].border = bd
def set_size():
"""
设置单元格的宽度和高度
:return:
"""
# 设置指定列的高宽度
sheet.column_dimensions['A'].width = 20
# 设置指定行的高度
sheet.row_dimensions[1].height = 45
if __name__ == '__main__':
set_font()
set_align_style()
wb.save('1.xlsx')
from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
# 1.打开工作簿
wb = openpyxl.load_workbook('1.xlsx')
sheet = wb.active
def set_font():
"""
设置单元格字体样式
Font(
name=None, # 字体名,可以用字体名字的字符串
strike=None, # 删除线,True/False
color=None, # 文字颜色
size=None, # 字号
bold=None, # 加粗, True/False
italic=None, # 倾斜,Tue/False
underline=None # 下划线, 'singleAccounting', 'double', 'single', 'doubleAccounting'
)
:return:
"""
font1 = Font(
size=20,
italic=True,
color='ff0000',
bold=True,
)
sheet['A1'] = '11111'
sheet['A1'].font = font1
def set_fill_style():
"""
设置单元格填充样式
PatternFill(
# 设置填充样式: 'darkGrid', 'darkTrellis', 'darkHorizontal', 'darkGray', 'lightDown', 'lightGray', 'solid', 'lightGrid', 'gray125', 'lightHorizontal', 'lightTrellis', 'darkDown', 'mediumGray', 'gray0625', 'darkUp', 'darkVertical', 'lightVertical', 'lightUp'
fill_type=None,
# 设置填充颜色
start_color=None
)
:return:
"""
fill = PatternFill(
fill_type='solid',
start_color='ffff00'
)
sheet['A1'].fill = fill
def set_align_style():
"""
设置单元格对齐样式
Alignment(
horizontal='right', # 水平方向:center, left, right
vertical='top' # 垂直方向: center, top, bottom
)
:return:
"""
al = Alignment(
horizontal='center', # 水平方向:center, left, right
vertical='center' # 垂直方向: center, top, bottom
)
sheet['A1'].alignment = al
def set_border_style():
"""
设置边框样式
Side(
border_style='thin',
color='0000ff'
)
Border(left=None, right=None, top=None, bottom=None)
"""
side = Side(border_style='thin', color='0000ff')
bd = Border(left=side, right=side, top=side, bottom=side)
sheet['B2'].border = bd
def set_size():
"""
设置单元格的宽度和高度
:return:
"""
# 设置指定列的高宽度
sheet.column_dimensions['A'].width = 20
# 设置指定行的高度
sheet.row_dimensions[1].height = 45
if __name__ == '__main__':
set_font()
set_align_style()
wb.save('1.xlsx')
系统相关
win32
键盘
import pyperclip
import win32api
import win32con
import win32api
import win32con
剪贴板
# 复制到剪贴板
pyperclip.copy(image_path)
# 粘贴
pyperclip.paste()
pyperclip.copy(image_path)
# 粘贴
pyperclip.paste()
按键
# ctrl(17) + V(86)
win32api.keybd_event(17, 0, 0, 0)
win32api.keybd_event(86, 0, 0, 0)
# 松开按键
win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(17, 0, 0, 0)
win32api.keybd_event(86, 0, 0, 0)
# 松开按键
win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
按键对照表
https://www.cnblogs.com/q455674496/p/13690871.html
鼠标
监听
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/7/25 15:05
# @Author : YXH
# @Email : 874591940@qq.com
# @desc : ...
# from pynput.keyboard import Listener
#
#
# def press(key):
# try:
# print(key.char)
# except Exception as e:
# print(key, e)
#
#
# with Listener(on_press=press) as listener:
# listener.join()
import time
import pythoncom
import PyHook3
import win32gui
import win32process
import psutil
from ctypes import *
import win32clipboard
user32 = windll.user32
kernel32 = windll.kernel32
psapi = windll.psapi
current_window = None
def on_mouse_listener(event):
"""
鼠标点击监听事件
:param event: 事件对象
:type event: PyHook3.HookManager.MouseEvent
:return:
:rtype: bool
"""
info = {
'messageName': event.MessageName, # 事件名称,例如:mouse left down,mouse right down
'message': event.Message, # windows消息常量,例如:左键513,右键516
'time': event.Time, # 事件发生的时间戳,该时间戳:系统已启动的时间
'timeStr': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), # 事件发生的时间戳
'window': event.Window, # 窗口句柄
'windowName': event.WindowName, # 窗口标题
'position': event.Position, # 事件发生时相对于整个屏幕的坐标
'wheel': event.Wheel, # 鼠标滚轮
'injected': event.Injected, # 判断这个事件是否由程序方式生成,而不是正常的人为触发。
'visiable': win32gui.IsWindowVisible(event.Window), # 窗口是否可见
'enable': win32gui.IsWindowEnabled(event.Window) # 窗口是否可用
}
print(info)
print(get_process_info(info['window']))
print(get_process_info2())
print('-' * 100)
return True
def on_keyboard_listener(event):
"""
键盘按下监听事件
:param event: 事件对象
:type event: PyHook3.HookManager.KeyboardEvent
:return:
:rtype: bool
"""
info = {
'messageName': event.MessageName, # 同上,共同属性不再赘述
'message': event.Message, # windows消息常量,例如:A键256
'time': event.Time, # 事件发生的时间戳,该时间戳:系统已启动的时间
'timeStr': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), # 事件发生的时间戳
'window': event.Window, # 窗口句柄
'windowName': event.WindowName, # 窗口名称
# 有大小写,根据实际输入的字符
'ascii': event.Ascii, # 按键的ASCII码,例如:97(a键),65(A键)
'ascii_chr': chr(event.Ascii), # ASCII码对应的字符,例如:a键(97),A键(65)
# 没有大小写,根据键盘的名称
'key': event.Key, # 按键的名称,例如:A键(65)
'keyID': event.KeyID, # 按键的虚拟键值,例如:65(A键)
'scanCode': event.ScanCode, # 按键扫描码
'extended': event.Extended, # 判断是否为增强键盘的扩展键
'injected': event.Injected,
'alt': event.Alt, # 是某同时按下Alt
'transition': event.Transition, # 判断转换状态
'visiable': win32gui.IsWindowVisible(event.Window), # 窗口是否可见
'enable': win32gui.IsWindowEnabled(event.Window) # 窗口是否可用
}
global current_window
# 检查目标是否切换了窗口
if event.WindowName != current_window:
print('前一个窗口:{};当前窗口:{},可见:{},可用:{}'.format(current_window,
event.WindowName,
win32gui.IsWindowVisible(event.Window),
11))
current_window = event.WindowName
# 普通按键
if 32 < event.Ascii < 127:
print('普通按键:按下了{}键,符号为:{}'.format(event.Key, chr(event.Ascii)))
# 特殊按键
else:
# 如果是CTRL+V,则获取剪贴板内容
if event.Key == 'v':
win32clipboard.OpenClipboard()
pasted_value = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print('粘贴板内容为:{}'.format(pasted_value))
# 换行
elif event.Key == 'Tab':
print('特殊按键:按下了换行键')
# 回车
elif event.Key == 'Return':
print('特殊按键:按下了回车键')
# Backspace
elif event.Key == 'Back':
print('特殊按键:按下了回退键')
# Delete
elif event.Key == 'Delete':
print('特殊按键:按下了删除键')
# Insert
elif event.Key == 'Insert':
print('特殊按键:按下了插入键')
else:
print('特殊按键:按下了{}键'.format(event.Key))
print(info)
print(get_process_info(info['window']))
print(get_process_info2())
print('-' * 100)
return True
def get_process_info(window_id):
"""
根据窗口句柄id获取窗口进程信息
:param window_id: 窗口句柄id
:type window_id: int
:return: 窗口进程信息
:rtype: dict
"""
thread_id, process_id = win32process.GetWindowThreadProcessId(window_id)
process = psutil.Process(process_id)
return {
'thread_id': thread_id,
'process_id': process_id,
'process_name': process.name(),
'window_name': win32gui.GetWindowText(window_id),
}
def get_process_info2():
"""
获取当前进程的相关信息
:return:
"""
# 获取最上层的窗口句柄
hwnd = user32.GetForegroundWindow() # 获得前台窗口句柄
pid = c_ulong(0)
user32.GetWindowThreadProcessId(hwnd, byref(pid))
process_id = "%d" % pid.value
# 申请内存
executable = create_string_buffer(1024)
h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512) # 获得进程名
# 读取窗口标题
window_title = create_string_buffer(512)
# length = user32.GetWindowTextA(hwnd, byref(window_title), 512) # 获得窗口名
# 关闭handles
kernel32.CloseHandle(hwnd)
kernel32.CloseHandle(h_process)
return {
'process_id': process_id,
'process_name': executable.value.decode('gbk'),
'window_name': window_title.value.decode('gbk')
}
def run():
# 创建构造函数管理器
hm = PyHook3.HookManager()
# 鼠标事件:
# MouseAll
# MouseAllButtons
# MouseAllButtonsUp
# MouseAllButtonsDown
# MouseAllButtonsDbl
# MouseWheel
# MouseMove
# MouseLeftUp
# MouseLeftDown
# MouseLeftDbl
# MouseRightUp
# MouseRightDown
# MouseRightDbl
# MouseMiddleUp
# MouseMiddleDown
# MouseMiddleDbl
# 键盘事件:
# KeyUp
# KeyDown
# KeyChar
# KeyAll
# 绑定鼠标、键盘监听事件的回调函数
hm.MouseAllButtonsDown = on_mouse_listener
hm.KeyDown = on_keyboard_listener
# 设置鼠标、键盘钩子
hm.HookMouse()
hm.HookKeyboard()
# 取消鼠标、键盘钩子
# hm.UnhookMouse()
# hm.UnhookKeyboard()
# 循环监听
pythoncom.PumpMessages()
if __name__ == '__main__':
run()
# -*- coding: utf-8 -*-
# @Time : 2021/7/25 15:05
# @Author : YXH
# @Email : 874591940@qq.com
# @desc : ...
# from pynput.keyboard import Listener
#
#
# def press(key):
# try:
# print(key.char)
# except Exception as e:
# print(key, e)
#
#
# with Listener(on_press=press) as listener:
# listener.join()
import time
import pythoncom
import PyHook3
import win32gui
import win32process
import psutil
from ctypes import *
import win32clipboard
user32 = windll.user32
kernel32 = windll.kernel32
psapi = windll.psapi
current_window = None
def on_mouse_listener(event):
"""
鼠标点击监听事件
:param event: 事件对象
:type event: PyHook3.HookManager.MouseEvent
:return:
:rtype: bool
"""
info = {
'messageName': event.MessageName, # 事件名称,例如:mouse left down,mouse right down
'message': event.Message, # windows消息常量,例如:左键513,右键516
'time': event.Time, # 事件发生的时间戳,该时间戳:系统已启动的时间
'timeStr': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), # 事件发生的时间戳
'window': event.Window, # 窗口句柄
'windowName': event.WindowName, # 窗口标题
'position': event.Position, # 事件发生时相对于整个屏幕的坐标
'wheel': event.Wheel, # 鼠标滚轮
'injected': event.Injected, # 判断这个事件是否由程序方式生成,而不是正常的人为触发。
'visiable': win32gui.IsWindowVisible(event.Window), # 窗口是否可见
'enable': win32gui.IsWindowEnabled(event.Window) # 窗口是否可用
}
print(info)
print(get_process_info(info['window']))
print(get_process_info2())
print('-' * 100)
return True
def on_keyboard_listener(event):
"""
键盘按下监听事件
:param event: 事件对象
:type event: PyHook3.HookManager.KeyboardEvent
:return:
:rtype: bool
"""
info = {
'messageName': event.MessageName, # 同上,共同属性不再赘述
'message': event.Message, # windows消息常量,例如:A键256
'time': event.Time, # 事件发生的时间戳,该时间戳:系统已启动的时间
'timeStr': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())), # 事件发生的时间戳
'window': event.Window, # 窗口句柄
'windowName': event.WindowName, # 窗口名称
# 有大小写,根据实际输入的字符
'ascii': event.Ascii, # 按键的ASCII码,例如:97(a键),65(A键)
'ascii_chr': chr(event.Ascii), # ASCII码对应的字符,例如:a键(97),A键(65)
# 没有大小写,根据键盘的名称
'key': event.Key, # 按键的名称,例如:A键(65)
'keyID': event.KeyID, # 按键的虚拟键值,例如:65(A键)
'scanCode': event.ScanCode, # 按键扫描码
'extended': event.Extended, # 判断是否为增强键盘的扩展键
'injected': event.Injected,
'alt': event.Alt, # 是某同时按下Alt
'transition': event.Transition, # 判断转换状态
'visiable': win32gui.IsWindowVisible(event.Window), # 窗口是否可见
'enable': win32gui.IsWindowEnabled(event.Window) # 窗口是否可用
}
global current_window
# 检查目标是否切换了窗口
if event.WindowName != current_window:
print('前一个窗口:{};当前窗口:{},可见:{},可用:{}'.format(current_window,
event.WindowName,
win32gui.IsWindowVisible(event.Window),
11))
current_window = event.WindowName
# 普通按键
if 32 < event.Ascii < 127:
print('普通按键:按下了{}键,符号为:{}'.format(event.Key, chr(event.Ascii)))
# 特殊按键
else:
# 如果是CTRL+V,则获取剪贴板内容
if event.Key == 'v':
win32clipboard.OpenClipboard()
pasted_value = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
print('粘贴板内容为:{}'.format(pasted_value))
# 换行
elif event.Key == 'Tab':
print('特殊按键:按下了换行键')
# 回车
elif event.Key == 'Return':
print('特殊按键:按下了回车键')
# Backspace
elif event.Key == 'Back':
print('特殊按键:按下了回退键')
# Delete
elif event.Key == 'Delete':
print('特殊按键:按下了删除键')
# Insert
elif event.Key == 'Insert':
print('特殊按键:按下了插入键')
else:
print('特殊按键:按下了{}键'.format(event.Key))
print(info)
print(get_process_info(info['window']))
print(get_process_info2())
print('-' * 100)
return True
def get_process_info(window_id):
"""
根据窗口句柄id获取窗口进程信息
:param window_id: 窗口句柄id
:type window_id: int
:return: 窗口进程信息
:rtype: dict
"""
thread_id, process_id = win32process.GetWindowThreadProcessId(window_id)
process = psutil.Process(process_id)
return {
'thread_id': thread_id,
'process_id': process_id,
'process_name': process.name(),
'window_name': win32gui.GetWindowText(window_id),
}
def get_process_info2():
"""
获取当前进程的相关信息
:return:
"""
# 获取最上层的窗口句柄
hwnd = user32.GetForegroundWindow() # 获得前台窗口句柄
pid = c_ulong(0)
user32.GetWindowThreadProcessId(hwnd, byref(pid))
process_id = "%d" % pid.value
# 申请内存
executable = create_string_buffer(1024)
h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512) # 获得进程名
# 读取窗口标题
window_title = create_string_buffer(512)
# length = user32.GetWindowTextA(hwnd, byref(window_title), 512) # 获得窗口名
# 关闭handles
kernel32.CloseHandle(hwnd)
kernel32.CloseHandle(h_process)
return {
'process_id': process_id,
'process_name': executable.value.decode('gbk'),
'window_name': window_title.value.decode('gbk')
}
def run():
# 创建构造函数管理器
hm = PyHook3.HookManager()
# 鼠标事件:
# MouseAll
# MouseAllButtons
# MouseAllButtonsUp
# MouseAllButtonsDown
# MouseAllButtonsDbl
# MouseWheel
# MouseMove
# MouseLeftUp
# MouseLeftDown
# MouseLeftDbl
# MouseRightUp
# MouseRightDown
# MouseRightDbl
# MouseMiddleUp
# MouseMiddleDown
# MouseMiddleDbl
# 键盘事件:
# KeyUp
# KeyDown
# KeyChar
# KeyAll
# 绑定鼠标、键盘监听事件的回调函数
hm.MouseAllButtonsDown = on_mouse_listener
hm.KeyDown = on_keyboard_listener
# 设置鼠标、键盘钩子
hm.HookMouse()
hm.HookKeyboard()
# 取消鼠标、键盘钩子
# hm.UnhookMouse()
# hm.UnhookKeyboard()
# 循环监听
pythoncom.PumpMessages()
if __name__ == '__main__':
run()
文件
删除文件
import os
os.remove(path) # 这个路径是一个文件夹,则会抛出OSError的错误
os.remove(path) # 这个路径是一个文件夹,则会抛出OSError的错误
import os
os.unlink(path) # unlink的功能和remove一样是删除一个文件,但是删除一个删除一个正在使用的文件会报错。
os.unlink(path) # unlink的功能和remove一样是删除一个文件,但是删除一个删除一个正在使用的文件会报错。
删除文件夹
import os
os.rmdir(path) # 文件夹需要时空的才能被删除
os.rmdir(path) # 文件夹需要时空的才能被删除
递归删除
import shutil
shutil.rmtree(path)
shutil.rmtree(path)
import os
os.removedirs(path) # 递归地删除目录。如果子目录成功被删除,则将会成功删除父目录,子目录没成功删除,将抛异常。
os.removedirs(path) # 递归地删除目录。如果子目录成功被删除,则将会成功删除父目录,子目录没成功删除,将抛异常。
selenium
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
删除运行时的cmd界面
修改\Lib\site-packages\selenium\webdriver\common\service.py
将
from subprocess import PIPE
修改为
from subprocess import PIPE,CREATE_NO_WINDOW
from subprocess import PIPE
修改为
from subprocess import PIPE,CREATE_NO_WINDOW
将
self.process = subprocess.Popen(cmd, env=self.env,
close_fds=platform.system() != 'Windows',
stdout=self.log_file,
stderr=self.log_file,
stdin=PIPE)
修改为
self.process = subprocess.Popen(cmd, env=self.env,
close_fds=platform.system() != 'Windows',
stdout=self.log_file,
stderr=self.log_file,
stdin=PIPE, creationflags=CREATE_NO_WINDOW)
self.process = subprocess.Popen(cmd, env=self.env,
close_fds=platform.system() != 'Windows',
stdout=self.log_file,
stderr=self.log_file,
stdin=PIPE)
修改为
self.process = subprocess.Popen(cmd, env=self.env,
close_fds=platform.system() != 'Windows',
stdout=self.log_file,
stderr=self.log_file,
stdin=PIPE, creationflags=CREATE_NO_WINDOW)
地址栏
about:version - 显示当前版本
about:memory - 显示本机浏览器内存使用状况
about:plugins - 显示已安装插件
about:histograms - 显示历史记录
about:dns - 显示DNS状态
about:cache - 显示缓存页面
about:gpu -是否有硬件加速
chrome://extensions/ - 查看已经安装的扩展
about:memory - 显示本机浏览器内存使用状况
about:plugins - 显示已安装插件
about:histograms - 显示历史记录
about:dns - 显示DNS状态
about:cache - 显示缓存页面
about:gpu -是否有硬件加速
chrome://extensions/ - 查看已经安装的扩展
添加启动参数
options = ChromeOptions()
# 接管已打开的浏览器
# chrome.exe --remote-debugging-port=9222
# options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
options.debugger_address('127.0.0.1:9222')
# 将浏览器数据保存到指定位置
# chrome.exe --user-data-dir='......'
# options.add_argument(r'--user-data-dir={}'.format(chrome_data_path))
# 添加UA
options.add_argument(user_agent)
# 无窗口化
# options.add_argument('--headless')
# 指定浏览器分辨率
# options.add_argument('window-size=1920x3000')
# 最大化
options.add_argument('--start-maximized')
# 浏览器全屏
# options.add_argument('start-fullscreen')
# 谷歌文档提到需要加上这个属性来规避bug
options.add_argument('--disable-gpu')
# 隐藏滚动条, 应对一些特殊页面
# options.add_argument('--hide-scrollbars')
# 以最高权限运行
options.add_argument('--no-sandbox')
# 在窗口上不出现‘自动化测试’提示
options.add_argument('--disable-infobars')
# 不加载图片, 提升速度
# options.add_argument('blink-settings=imagesEnabled=false')
# 禁用JavaScript
# options.add_argument("--disable-javascript")
# 手动指定使用的浏览器位置
# options.binary_location = chrome_path
# 代理
# options.add_argument('--porxy-server=127.0.0.1:8888') # 无认证
# 接管已打开的浏览器
# chrome.exe --remote-debugging-port=9222
# options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
options.debugger_address('127.0.0.1:9222')
# 将浏览器数据保存到指定位置
# chrome.exe --user-data-dir='......'
# options.add_argument(r'--user-data-dir={}'.format(chrome_data_path))
# 添加UA
options.add_argument(user_agent)
# 无窗口化
# options.add_argument('--headless')
# 指定浏览器分辨率
# options.add_argument('window-size=1920x3000')
# 最大化
options.add_argument('--start-maximized')
# 浏览器全屏
# options.add_argument('start-fullscreen')
# 谷歌文档提到需要加上这个属性来规避bug
options.add_argument('--disable-gpu')
# 隐藏滚动条, 应对一些特殊页面
# options.add_argument('--hide-scrollbars')
# 以最高权限运行
options.add_argument('--no-sandbox')
# 在窗口上不出现‘自动化测试’提示
options.add_argument('--disable-infobars')
# 不加载图片, 提升速度
# options.add_argument('blink-settings=imagesEnabled=false')
# 禁用JavaScript
# options.add_argument("--disable-javascript")
# 手动指定使用的浏览器位置
# options.binary_location = chrome_path
# 代理
# options.add_argument('--porxy-server=127.0.0.1:8888') # 无认证
# 切换到手机页面
# options.add_experimental_option('mobileEmulation', {'deviceName': 'iPhone 6/7/8'})
# 设置默认下载目录
# options.add_experimental_option('prefs', {'download.default_directory': download_path})
# 设置开发者模式启动,该模式下webdriver属性为正常值
# options.add_experimental_option('excludeSwitches', ['enable-automation'])
# 禁用浏览器弹窗
# options.add_experimental_option('prefs', {'profile.default_content_setting_values': {'notifications': 2}})
添加扩展应用
# 代理
# options.add_extension(create_proxy_auth_extension('host', 'port', 'user', 'password')) # 有认证
# 添加crx插件
# options.add_extension('xx.crx')
# options.add_extension(create_proxy_auth_extension('host', 'port', 'user', 'password')) # 有认证
# 添加crx插件
# options.add_extension('xx.crx')
代理
background.js
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "mimvp_proxy_host",
port: parseInt(mimvp_proxy_port)
},
bypassList: ["mimvp.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "mimvp_username",
password: "mimvp_password"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
manifest.json
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "mimvp_proxy_host",
port: parseInt(mimvp_proxy_port)
},
bypassList: ["mimvp.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "mimvp_username",
password: "mimvp_password"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
create_proxy_auth_extension.py
import random
import string
import zipfile
def create_proxy_auth_extension(proxy_host, proxy_port, proxy_username, proxy_password, scheme='http',
plugin_path=None):
if plugin_path is None:
plugin_path = r'{}_{}@http-dyn.dobel.com_9020.zip'.format(proxy_username, proxy_password)
manifest_json = """
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Dobel Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
"""
background_js = string.Template(
"""
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "${scheme}",
host: "${host}",
port: parseInt(${port})
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "${username}",
password: "${password}"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
"""
).substitute(
host=proxy_host,
port=proxy_port,
username=proxy_username,
password=proxy_password,
scheme=scheme,
)
with zipfile.ZipFile(plugin_path, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_path
options.add_extension(create_proxy_auth_extension('host', 'port', 'user', 'password'))
wait
self.wait.until(ec.presence_of_element_located((By.XPATH, partten)))
元素
获取元素
chrome.find_element_by_xpath(partten)
获取属性
element.get_attribute('src')
点击
js点击
chrome.execute_script("arguments[0].click();", element)
普通点击
element.click()
切换iframe
验证码
超级鹰
# 创建超级鹰对象
chaojiying = Chaojiying_Client(username, password, softid)
# 读取验证码
image_data = open('1.jpg', 'rb').read()
# 识别验证码,第二个参数为验证码类型
response = chaojiying.PostPic(image_data, 1007)
# 获取识别的验证码
verification_code = response['pic_str']
# 若识别错误
chaojiying.ReportError(response['pic_id'])
chaojiying = Chaojiying_Client(username, password, softid)
# 读取验证码
image_data = open('1.jpg', 'rb').read()
# 识别验证码,第二个参数为验证码类型
response = chaojiying.PostPic(image_data, 1007)
# 获取识别的验证码
verification_code = response['pic_str']
# 若识别错误
chaojiying.ReportError(response['pic_id'])
返回的参数类型
{"err_no":0,"err_str":"OK","pic_id":"1662228516102","pic_str":"8vka","md5":"35d5c7f6f53223fbdc5b72783db0c2c0"}
0 条评论
下一页