DrissionPage/docs/使用方法/保存配置.md
2021-12-10 19:02:42 +08:00

89 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

因 chrome 和 headers 配置繁多,故设置一个 ini 文件专门用于保存常用配置,你可使用 OptionsManager 对象获取和保存配置,用 DriverOptions 对象修改 chrome 配置。你也可以保存多个 ini
文件,按不同项目须要调用。
Tips建议把常用配置文件保存到别的路径以防本库升级时配置被重置。
# ini 文件内容
ini 文件默认拥有三部分配置paths、chrome_options、session_options初始内容如下。
```ini
[paths]
; chromedriver.exe路径
chromedriver_path =
; 临时文件夹路径,用于保存截图、文件下载等
tmp_path =
[chrome_options]
; 已打开的浏览器地址和端口如127.0.0.1:9222
debugger_address =
; chrome.exe路径
binary_location =
; 配置信息
arguments = [
; 静音
'--mute-audio',
; 不使用沙盒
'--no-sandbox',
; 谷歌文档提到需要加上这个属性来规避bug
'--disable-gpu',
; 忽略警告
'ignore-certificate-errors',
; 不显示信息栏
'--disable-infobars'
]
; 插件
extensions = []
; 实验性配置
experimental_options = {
'prefs': {
; 下载不弹出窗口
'profile.default_content_settings.popups': 0,
; 无弹窗
'profile.default_content_setting_values': {'notifications': 2},
; 禁用PDF插件
'plugins.plugins_list': [{"enabled": False, "name": "Chrome PDF Viewer"}]
},
; 设置为开发者模式,防反爬虫
'excludeSwitches': ["enable-automation"],
'useAutomationExtension': False
}
[session_options]
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection": "keep-alive",
"Accept-Charset": "utf-8;q=0.7,*;q=0.7"
}
```
# OptionsManager 对象
OptionsManager 对象用于读取、设置和保存配置。
```python
manager.paths # 以字典形式返回路径设置
manager.chrome_options # 以字典形式返回chrome设置
manager.session_options # 以字典形式返回session设置
manager.get_value(section, item) # 获取某个配置的值
manager.get_option(section) # 以字典格式返回配置全部属性
manager.set_item(section, item, value) # 设置配置属性
manager.manager.save() # 保存当前打开的 ini 文件
manager.save('D:\\settings.ini') # 保存到指定路径 ini 文件
manager.save('default') # 保存当前设置到默认 ini 文件
```
# 使用示例
```python
from DrissionPage.configs import *
options_manager = OptionsManager() # 从默认ini文件创建OptionsManager对象
options_manager = OptionsManager('D:\\settings.ini') # 从其它ini文件创建OptionsManager对象
driver_path = options_manager.get_value('paths', 'chromedriver_path') # 读取路径信息
options_manager.save() # 保存当前打开的 ini 文件
options_manager.save('D:\\settings.ini') # 保存到指定路径 ini 文件
drission = Drission(ini_path='D:\\settings.ini') # 使用指定 ini 文件创建对象
```