沙滩星空的博客沙滩星空的博客

Python使用Selenium操作谷歌浏览器

Selenium简介

Selenium 是一个免费的分布式的自动化测试工具,支持多平台:windows、linux、MAC ,支持多浏览器:ie、ff、safari、opera、chrome,多语言C、 java、ruby、python、或都是C#,同时也支持phantomJS无界面浏览器。

安装Selenium

pip install Selenium

安装浏览器驱动

Selenium3.x调用浏览器必须有一个webdriver驱动文件

Chrome驱动:chromedrive
Firefox驱动: geckodriver

ChromeDrive 的安装和使用

要先安装Chrome浏览器,然后安装ChromeDriver。

官网(有版本对应关系,如果打不开,记得都用最新版本基本OK):
https://sites.google.com/a/chromium.org/chromedriver
https://sites.google.com/chromium.org/driver/

下载地址:
https://chromedriver.storage.googleapis.com/index.html
或淘宝chromedriver镜像下载
https://npm.taobao.org/mirrors/chromedriver/

下载完成后,将ChromeDriver的可执行文件配置到环境变量下。
在Windows下,建议直接将chromedriver.exe文件拖到Python的Scripts目录下。
Python代码验证:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
print(driver.title)
print("===这只是一个测试,不必惊慌=== ")
driver.quit()

运行后,如果弹出Chrome浏览器,则证明配置没问题。否则,请检查配置。


设置启动参数

from selenium import webdriver
from selenium.webdriver import ChromeOptions
# from selenium.webdriver.chrome.options import Options

option = ChromeOptions()

# Headless Chrome 谷歌浏览器无界面模式
option.add_argument("--headless") # 此项必填,指定无头模式。其他为选填
option.add_argument('--no-sandbox') # 解决DevToolsActivePort文件不存在的报错
option.add_argument('--disable-gup') #谷歌文档提到需要加上这个属性来规避bug
option.add_argument('blink-settings=imagesEnabled=false') #不加载图片, 提升速度

# 自定义http请求头
option.add_argument('lang=zh_CN.UTF-8')
option.add_argument('user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"')

# 自定义用户数据目录
option.add_argument("--user-data-dir=runtime/google_chrome_user_data")

#手动指定使用的浏览器位置
option.binary_location = "C:\Program Files\Google\Chrome\Application\chrome.exe"
# 指定浏览器分辨率
options.add_argument('window-size=1920x3000')

browser = webdriver.Chrome(options=option)
browser.set_window_size(1920,1080)
url = 'https://www.baidu.com'
browser.get(url)

# browser.get_screenshot_as_file("baidu0.png")
browser.save_screenshot('baidu1.png')
browser.quit()

阿里云PyPI 镜像

~/.pip/pip.conf

[global]
index-url = https://mirrors.aliyun.com/pypi/simple/

[install]
trusted-host=mirrors.aliyun.com

官网介绍 https://developers.google.com/web/updates/2017/04/headless-chrome
selenium之chrome无头模式 https://blog.csdn.net/lingxiyizhi_ljx/article/details/105239806
selenium无界面chromedriver https://www.cnblogs.com/z-x-y/p/9026226.html

PyPI阿里云镜像 https://developer.aliyun.com/mirror/pypi
ChromeDriver的安装和使用 https://www.cnblogs.com/xuyingzhong/p/9345474.html
Python Selenium库的使用 https://blog.csdn.net/weixin_36279318/article/details/79475388

未经允许不得转载:沙滩星空的博客 » Python使用Selenium操作谷歌浏览器

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址