1 搭建环境
1.1 安装 selenium
pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple1.2 安装浏览器驱动
可以参考另一篇文章**“chromedriver下载与安装方法**”
https://blog.csdn.net/one_bird_/article/details/131592362
整体步骤如下:
下载路径:
http://npm.taobao.org/mirrors/chromedriver/
# 让 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
#使用Chrome的DevTools协议来控制浏览器屏蔽Chrome浏览器的"Chrome正受到自动测试软件控制"提示 from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.chrome import options from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) chrome_options.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(options=chrome_options) driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) driver.get(xxxxxx) html = driver.page_source6.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)