selenuim行为链
具体url参考:http://selenium-python.readthedocs.io/api.html
行为链事例
from selenium import webdriver
from selenium.webdriver import ActionChains
driver =webdriver.Chrome()
driver.get('https://www.baidu.com/')
inputTag =driver.find_element_by_id('kw')
button =driver.find_element_by_id('su')
actions =ActionChains(driver)
actions.move_to_element(inputTag)
actions.send_keys_to_element(inputTag,'五一节快乐')
actions.perform()
行为链后需要点击按钮button才可以,方法有两个,一个是在行为链之后——button.click()
方法2:在行为链中将鼠标转到button再click()
右键单击——context_click(element)
用selenuim获取cookie
from selenium import webdriver
import time
driver =webdriver.Chrome()
driver.get('https://www.baidu.com/')
cookies =driver.get_cookies()
for cookie in cookies:
print(cookie)
有用的是name和value
用这里的cookie来模拟登录qq空间
到达qq快速登录,点击头像登录空间
用json解析看数据
driver =webdriver.Chrome()
driver.get('qq空间')
button =driver.find_element_by_class_name('face')
button.click()
cookies =driver.get_cookies()
print(type(cookies))
print('--'*50)
jsoncookies =json.dumps(cookies)
print(type(jsoncookies))
此时获取的cookie可以看到是在列表里面
正常cookie
此时,cookie获取了,为了保证cookie的获取,可以time.sleep()几秒等待加载完成
模拟登录
selenuim页面等待
方法一:time.sleep()
from selenium import webdriver
import time
driver =webdriver.Chrome()
driver.get('https://www.baidu.com/')
time.sleep(2)
driver.find_element_by_id('kw').send_keys('python')
隐形等待——implicitly_wait()
from selenium import webdriver
import time
driver =webdriver.Chrome()
driver.get('https://www.baidu.com/')
driver.implicitly_wait()
driver.find_element_by_id('kw').send_keys('python')
显示等待
driver.find_element_by_id("qd_closeDefaultWarningWindowDialog_id").click()
button =driver.find_element_by_id("query_ticket")
button.click()
driver.find_element_by_id("qd_closeDefaultWarningWindowDialog_id").click()
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(driver,50).until(
EC.text_to_be_present_in_element_value((By.ID,"fromStationText"),'长沙')
)
WebDriverWait(driver,50).until(
EC.text_to_be_present_in_element_value((By.ID,"toStationText"),'北京')
)
button =driver.find_element_by_id("query_ticket")
button.click()
此时满足条件(长沙到北京)显示等待条件满足,直接不用手动点查询(代码写了)就可以得到结果
多窗口
如果直接这样,会覆盖旧页面,而不是两个窗口
execute_script(“window.open(url)”)
但是此时问题在于,做的操作仍然是百度,当执行close()的时候,关闭的是百度,input标签输入的也是百度
这时要切换窗口才可以操作豆瓣
switch_to.window(driver.window_handles[切换窗口索引值])