1.selenium模块
(1)selenium模块简介
selenium是一个基于浏览器自动化的模块,可以便捷地获取动态加载的数据,便捷地实现模拟登录。
功能:
发起请求:get(url)
标签定位:find
标签交互:send_keys(‘xxx’)
执行js程序:excute_script(‘jscode’)
前进,后退:back(),forward()
关闭浏览器:quit()
(2)下载浏览器驱动(以chrome为例)
在chrome浏览器-帮助-关于google chrome中,可以看到chrome版本
在驱动下载链接 https://chromedriver.storage.googleapis.com/index.html中下载对应版本驱动
将exe程序放在如下目录下
定义一个selenium模块
from selenium import webdriver
bro=webdriver.Chrome(executable_path="../chromedriver/chromedriver"
(3)对于iframe的处理
以qq空间登陆界面为例,登录框是一个iframe子页面,使用selenium.find直接定位是定位不到的,所以需要先定位到iframe页面
#定位到iframe页面中
bro.switch_to.frame('login_frame')
(4)规避检测
一些网站会监测当前请求是否由selenium发出,需要规避检测
from selenium.webdriver import ChromeOptions
#实现规避检测
option=ChromeOptions()
option.add_experimental_option('excludeSwitches',['enable-automation'])
bro=webdriver.Chrome(executable_path="../chromedriver/chromedriver",options=option)
(5)案例
登录qq空间
在登录qq的情况下,点击头像就可登录
from selenium import webdriver
from time import sleep
#规避检测
from selenium.webdriver import ChromeOptions
#实现规避检测
option=ChromeOptions()
option.add_experimental_option('excludeSwitches',['enable-automation'])
bro=webdriver.Chrome(executable_path="../chromedriver/chromedriver",options=option)
bro.get('https://qzone.qq.com/')
#定位到iframe页面中
bro.switch_to.frame('login_frame')
sleep(2)
btn=bro.find_element_by_id('')#引号内填img_out_qq号
sleep(2)
btn.click()
sleep(10)
bro.quit()
成功登录