简介
selenium能实现让浏览器自动操作功能
使用条件
下载好对应浏览器的驱动,以谷歌为例
http://npm.taobao.org/mirrors/chromedriver/从上面下载对应版本浏览器的驱动
安装环境:pip install selenium
用法
导入:from selenium import webdriver
实例化一个浏览器对象:
chorn = webdriver.Chrome(executable_path=“下载的驱动路径位置”)
这个时候你的浏览器已经会自动打开了
发起请求,以某宝为例:chorn.get(“https://www.taobao.com”)
这个时候你的浏览器已经会自动打开,并且搜索这个网址
淘宝搜索:先找到对应的输入框标签,里面有个id标签对应值为q
即定位到这个输入框:search_input = chorn.find_element_by_id(“q”)
输入想要搜索的内容:search_input.send_keys(“充气娃娃”)
然后我们要点击:即要定位到点击按钮,里面有个calss标签内容为:btn-search tb-bg
我们用其中一个标签值就行了:btn = chorn.find_element_by_class_name(“btn-search”)
然后就是点击了:btn.click()
完成了,这个时候你如果执行代码,浏览器就会自动打开并搜索淘宝并进入,然后向输入框中输入数据并点击搜索
另外如果想执行js代码:
chorn.execute_script(“js代码”)
后退一步:chorn.back
前进一步:chorn.forward()
综上代码
from selenium import webdriver
import time
chorn = webdriver.Chrome(executable_path="./chromedriver.exe")
chorn.get("https://www.taobao.com")
search_input = chorn.find_element_by_id("q")
search_input.send_keys("交换机")
#chorn.execute_script("window.scrollTo(0,document.body.scrollHeight)")
btn = chorn.find_element_by_class_name("btn-search")
chorn.execute_script("window.scrollTo(0,document.body.scrollHeight)")
btn.click()
time.sleep(5)
chorn.quit()
进阶
突破frame限制
如果我想要定位的标签在iframe中,正常定位标签是不行的,需要使浏览器对象转换到作用域frame中
web.switch_to.frame(“login_frame”)
将浏览器对象作用域转换到id值为login_frame的frame作用域中,在此,就可以正常进行定位
模拟qq空间登录
from selenium import webdriver
from lxml import etree
from selenium.webdriver import ActionChains
import time
def mian():
web = webdriver.Chrome(executable_path="./chromedriver.exe")
web.get("https://qzone.qq.com/")
web.switch_to.frame("login_frame")
div = web.find_element_by_id("switcher_plogin")
div.click()
user = web.find_element_by_id("u")
pas = web.find_element_by_id("p")
user.send_keys("账号")
pas.send_keys("密码")
sub = web.find_element_by_id("login_button")
sub.click()
web.switch_to.frame("tcaptcha_iframe")
action = ActionChains(web)
tuo = web.find_element_by_id("tcaptcha_drag_thumb")
action.click_and_hold(tuo)
action.move_by_offset(164,0).perform()
action.release().perform()
web.close()
time.sleep(5)
if __name__ == "__main__":
mian()
因为qq空间想要账号密码登录就得按账号密码登录选项
而这个选项是作用在frame中,故先要转换:web.switch_to.frame(“login_frame”)
然后定位账号密码框: user = web.find_element_by_id(“u”)
pas = web.find_element_by_id(“p”)
点击后会要进行拖到验证:定位这个拖到按钮
action = ActionChains(web) : 创建一个动作对象,用来拖到按钮,参数为浏览器对象
action.click_and_hold(tuo) : 执行动作,点击并按住定位的tuo标签
action.move_by_offset(164,0).perform() : 移动坐标向左164像素,上下不移动,perform() 表示立即执行
action.release().perform() : 立即释放动作