selenium:
●概念:基于浏览器自动化的模块
●自动化:可以通过代码指定- 些列的行为动作,然后将其作用到浏览器中。
●pip install selenium
●selenium和爬虫之间的关联
■1.便捷的捕获到任意形式动态加载的数据(可见即可得)
■2.实现模拟登录
●selenium的弊端:
■效率低
环境变量:
是在操作系统中一个具有特定名字的对象,它包含了一个或者多个应用程序所将使用到的信息。例如Windows和DOS操作系统中的path环境变量,当要求系统运行一个程序而没有告诉它程序所在的完整路径时,系统除了在当前目录下面寻找此程序外,还应到path中指定的路径去找。用户通过设置环境变量,来更好的运行进程。
#在搜索结果页面进行滚轮向下滑动的操作(执行js操作: js注入)
bro.execute_script ( 'window.scrollTo( 0 , document.body.scrollHeight)' )
#如果通过find系列的函数进行标签定位, 如果标签是存在于iframe下面,则会定位失败 解决方案:使用switch to即可
bro.switch_to.frame('iframeResult' )
div_tag = bro.find_element_by_xpath('//*[@id= "draggable"]')
print(div_tag)
#对div_tag进行滑动操作
action = ActionChains(bro)
action.click_and_hold(div_tag) #点击且长按
for i in range(6):
#perform让动作链立即执行
action.move_by_offset(10,15).perform()
sleep(0.5)
action.release()
bro.quit()
●如何让selenium规避检测
■有的网站会检测请求是否为selenium发起,如果是的话则让该次请求失败
■规避检测的方法:
●selenium接管chrome浏览器
●实现步骤
■1.必须将你电脑中安装的谷歌浏览器的驱动程序所在的目录找到。且将目录添加到环境变量中。
■2.打开cmd, 在命令行中输入命令:
chrome.exe --remote-debugging-port=9222 --user-data-dir="一个空文件夹的目录" 指定执行结束后,会打开你本机安装好的谷歌浏览器。
■3.执行如下代码:可以使用下属代码接管步骤2打开的真实的浏览器
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 谷歌浏览器安装目录下执行
# chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile"
# 在打开的浏览器中输入 www.baidu.com
'''
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
option = Chromeoptions()
option.add_experimental_option('excludeSwitches',['enable-automation'])
driver = Chrome(options=option)
'''
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
chrome_driver = "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
driver = webdriver.Chrome(chrome_driver, options=chrome_options)
# 输出百度一下你就知道 表示接管成功了
print(driver.title)