1.设置无头模式(在显示器上不显示):
在options对象的add_argument()方法的参数中添加:–headless
options = webdriver.FirefoxOptions() options.add_argument('--headless') driver = webdriver.Firefox(service=s,options=options) driver.get('https://lcj.ink')
2.设置窗口界面大小(比如1200*600):
options.add_argument('--window-size=1200,600')
3.获取所有的cookie:
使用driver对象的get_cookies()方法,cookie会以列表的形式返回,列表的元素则为字典
driver.get('https://www.baidu.com') for cookie in driver.get_cookies() : print(cookie)
4.根据cookie的key获取value:
注意:cookies = { ‘value’:’key’ },value为键,key为值
在driver对象的get_cookie()的括号中添加参数key:
driver.get('https://www.baidu.com') print( driver.get_cookie('BA_HECTOR') )
5.删除所有的cookie:
使用driver对象中的delete_all_cookies()
driver.get('https://www.baidu.com') print(driver.get_cookies()) driver.delete_all_cookies() print(driver.get_cookies())
6.根据key删除对应的cookie:
使用driver对象中的delete_cookie(),在括号中添加参数key
driver.get('https://www.baidu.com') print(driver.get_cookie('BA_HECTOR')) driver.delete_cookie('BA_HECTOR') print(driver.get_cookie('BA_HECTOR'))
7.添加cookie:
使用driver对象中的add_cookie(),在括号中添加字典类型的数据:
driver.get('https://lcj.ink') cookie = { 'user':'abc', 'domain':'lcj.ink' } driver.add_cookie(cookie) print(driver.get_cookies())
8.利用js打开一个新的页面:
使用driver对象中的execute_script()来调用js,括号中可以添加js代码,
打开新页面的js代码为:
window.open(url)
使用selenium打开一个新的页面:
driver.get('https://lcj.ink') driver.excute_script("window.open('https://lcj.ink?p=615')")
9.切换新的页面:
使用driver对象的switch_to.window(),参数中使用driver.window_handles[],方括号中填入窗口的序号(0代表第一个窗口,1代表第二个窗口,依此类推)
driver.get('https://www.baidu.com') driver.excute_script('https://lcj.ink') driver.implicitly_wait(5) driver.switch_to.window(driver.window_handles[0]) #切换回百度
10.设置代理:
针对Chrome:使用options对象中的add_argument(),在其中添加 ‘–proxy-server=http://ip:端口’
options.add_argument('--proxy-server=http://abcd.com:1234') driver = webdriver.Chrome(service=s,chrome_options=options) driver.get('http://httpbin.org/ip')
针对Firefox:
我们需要先创建FirefoxOptions对象
profile = FirefoxOptions()
设置代理:
我们需要使用FirefoxOptions对象的set_preference(),括号中添加我们需要配置的内容:
profile.set_preference('network.proxy.type',1) #network.proxy.type为1时代表手动配置,为0时代表不使用代理 profile.set_preference('network.proxy.http','IP地址') #http中使用的代理服务器的IP地址 profile.set_preference('network.proxy.http_port',端口) #http中使用的代理服务器的端口,这里的端口格式为 整型(int) profile.set_preference('network.proxy.ssl','IP地址') #https中使用的代理服务器的IP地址 profile.set_preference('network.proxy.ssl_port',端口) #https中使用的代理服务器的端口,这里的端口格式为 整型(int)
然后,我们需要将我们的配置传入driver中:
driver = webdriver.Firefox(service=s,options=profile)
然后我们可以用webdriver打开http://httpbin.org/ip来检测IP地址:
driver.get('http://httpbin.org/ip')