selenium无界面操作浏览器
selenium的无界面化功能使用的模板代码,以后使用的时候,直接把这些配置复制过去就好了。
下面举了三种我常用的操作:
第一种:selenium自动去请求某个页面
第二种:selenium模拟登陆
第三种:selenium获取cookie
from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Optionschrome_options = Options()
chrome_options.add_argument('--no-sandbox') #解决DevToolsActivePort文件不存在的报错
chrome_options.add_argument('window-size=1920x3000') #指定浏览器分辨率
chrome_options.add_argument('--disable-gpu') #谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('--hide-scrollbars') #隐藏滚动条, 应对一些特殊页面
chrome_options.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度
chrome_options.add_argument('--headless') #浏览器不提供可视化页面. linux下如果系统不支持可视化不加这条会启动失败
chrome_options.binary_location = r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" #手动指定本机电脑使用的浏览器位置# 创建一个driver,进行后面的请求页面等操作,executable_path指定本机中chromedriver.exe的位置
driver=webdriver.Chrome(chrome_options=chrome_options, executable_path="D:/myq/chromedriver.exe") # 举例1:使用driver去请求页面
driver.get("http://hz.soolou.com/office_show_8933.html")# 举例2:driver去填写用户名和密码进行模拟登陆
driver.find_element_by_id("loginform-username").send_keys("dongyuqin")
driver.find_element_by_id("loginform-password").send_keys("dongyuqin")
# driver自动点击登陆按钮
driver.find_element_by_xpath("//div[@class='form-group']").click()# 举例3: driver自动获取cookie信息,这里可以将cookies添加到cookie池中去循环使用
cookies = driver.get_cookies()
# 打印获取的cookies信息
print(cookies)# 最后记得关闭driver
close = driver.close()
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
