亲宝软件园·资讯

展开

Selenium中的option使用示例

松勤吴老师 人气:0

在上一篇文章Selenium中免登录的实现方法一option中我们用到了option,而option的用法是很多的,本文举几个例子

关于无头浏览器,也属于option的一种,但我们单独开个篇幅讲一下

01. 无痕模式

from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_argument('--incognito')
driver = webdriver.Chrome(options=myoption)

02. 启动时窗口大小设置

from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_argument('--start-maximized')
driver = webdriver.Chrome(options=myoption)
from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_argument('--window-size=800,600')
driver = webdriver.Chrome(options=myoption)
from selenium import webdriver
import pyautogui
myoption = webdriver.ChromeOptions()
width,height = pyautogui.size()
myoption.add_argument(f'--window-size={round(width/3)},{round(height/3)}')
driver = webdriver.Chrome(options=myoption)

03. 去掉浏览器被自动化软件控制的提示

from selenium import webdriver
myoption = webdriver.ChromeOptions()
myoption.add_experimental_option("excludeSwitches", ["enable-automation"])
myoption.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=myoption)

04. 伪造user-agent

from selenium import webdriver
# from fake_useragent import UserAgent  # 以前是这个库,现在链接外部网站有点问题,就改用本地库了
from local_fake_useragent import UserAgent  # pip install local-fake-useragent

chrome_ua = UserAgent('chrome').rget
print(chrome_ua) # Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.16 SUSE/10.0.626.0 (KHTML, like Gecko) Chrome/10.0.626.0 Safari/534.16
options = webdriver.ChromeOptions()
options.add_argument(f'user-agent={chrome_ua}')
driver = webdriver.Chrome(options=options)
driver.get('https://cn.bing.com')

05. 禁止弹窗

iqiyi的首页打开的时候会弹出 允许禁止,这个可以ban掉

from selenium import webdriver
prefs = {
    'profile.default_content_setting_values': {
        'notifications': 2
    }
}
myoption = webdriver.ChromeOptions()
myoption.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(options=myoption)
driver.get('https://www.iqiyi.com/')

加载全部内容

相关教程
猜你喜欢
用户评论