稳扎稳打学爬虫08—Selenium的使用方法详解

1 搭建环境

1.1 安装 selenium

pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

1.2 安装浏览器驱动

首先,下载浏览器驱动:https://npm.taobao.org/mirrors/chromedriver,然后把解压的浏览器驱动 chromedriver 放在 python解释器所在的文件夹(python解释器所在的文件夹:cmd-----where python)中。

2 示例

# 让 selenium 启动谷歌浏览器
from selenium import webdriver 
# from selenium.webdriver import Chrome
# 1、创建浏览器对象
web = webdriver.Chrome() 
# web = Chrome()
#2、打开一个网址
web.get("http://www.baidu.com")

3 设置无头浏览器

from selenium.webdriver import Chrome
#准备好参数配置
opt  = Options()
opt.add_argument('--headless')
opt.add_argument('--disable-gpu')

web = Chrome(options = opt) #把参数配置设置到浏览器中,就变成了无头浏览器
web.get("http://www.baidu.com")

4 进行窗口切换

web.get("xxxxxxxx")
#在selenium中,新窗口默认是不进行切换的
#进行窗口切换
web.switch_to.window(driver.window_handles[-1])
#关闭子窗口
web.close()
#变更selenium的窗口视角,回到原来的窗口中
web.switch_to.window(driver.window_handles[0])

5 iframe中的内容获取

#如果页面中遇到iframe,需要先拿到iframe,然后切换到iframe视角,然后才可以拿数据
iframe = web.get('https://www.91kanju.com/vod-play/541-2-1.html')
web.switch_to.frame(iframe)
#切回原页面
web.switch_to.default_content()

6 程序被识别的解决办法

6.1 chrome的版本号小于88

#在启动浏览器的时候(此时没有加载任何网页内容),向页面嵌入js代码,去掉webdriver
web = Chrome()

web.execut_cdp_cmd("Page.asddScriptToEvaluateOnNewDocument"),{
	"source":"""
	navigator.webdriver = undefined
	Object.defineProperty(navigator,'webdriver',{
		get:() => undefined
	})
	"""
}
web.get(xxxxxx)

6.2 chrome的版本号大于88

option = Options()
# 可写可不写
#option.add_experimental_option('excludeSwitches',['enable-automatioin'])
option.add_argument('--disable-black-features = AutomationControlled')

web = Chrome(option = option)
web.get(xxxxxxx)

版权声明:本文为one_bird_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。