谷歌驅動(chromedriver)下載地址: http://chromedriver.storage.googleapis.com/index.html
from selenium import webdriver
browseDriver = webdriver.Phantomjs(executable_path="Phantomjs的驅動路徑")
browseDriver.get('https://www.baidu.com')
print(browseDriver.page_source)
print(browseDriver.current_url)
例子
導入 webdriver
from selenium import webdriver
要想調用鍵盤按鍵操作需要引入keys包
from selenium.webdriver.common.keys import Keys
import time
無界面瀏覽器相關設置
創建chrome參數對象
opt = webdriver.ChromeOptions()
把chrome設置成為無界面模式
opt.set_headless()
創建chrome無界面對象
driver = webdriver.Chrome(
options=opt, executable_path='/Users/ljh/Desktop/chromedriver'
)
創建chrome有界面對象
調用Chrome瀏覽器創建瀏覽器對像(指定一下位置)
driver = webdriver.Chrome(
executable_path='/Users/ljh/Desktop/chromedriver'
)
打開瀏覽器,模擬瀏覽器請求頁面
driver.get('http://www.baidu.com/')
獲取頁面的信息
html = driver.page_source
print(html)
獲取頁面名為 wrapper的id標簽的文本內容
data = driver.find_element_by_id("wrapper").text
獲取標簽的屬性
attrvaule = driver.find_element_by_id("wrapper").get_attribute('class')
打印數據內容
print(data)
打印標題數據
print(driver.title)
向百度的搜索框輸入搜索關鍵字
driver.find_element_by_id('kw').send_keys('美女')
百度搜索按鈕,click() 是模擬點擊
driver.find_element_by_id('su').click()
獲取當前頁面的cookies()
cookies = driver.get_cookies()
cookie = ''
for item in cookies:
cookie += item['name']+item['value']+' ;'
print(cookie[:-1])
全選輸入框中的內容ctrl+a
print(driver.find_element_by_id('kw').send_keys(Keys.CONTROL, 'a'))
ctrl+x 剪切輸入框內容
driver.find_element_by_id("kw").send_keys(Keys.CONTROL, 'x')
清空輸入框內容
driver.find_element_by_id('kw').clear()
輸入框重新輸入內容
driver.find_element_by_id('kw').send_keys('風景')
模擬回車鍵
driver.find_element_by_id('su').send_keys(Keys.RETURN)
獲取當前的url
currentUrl = driver.current_url
print(currentUrl)
截取網頁頁面(生成當前的頁面快照并保存)
driver.save_screenshot('baidu.png')
睡眠7秒
time.sleep(7)
關閉瀏覽器
driver.quit()
關閉當前頁面,如果只有一個頁面,會關閉瀏覽器
driver.close()
獲取id標簽值
element = driver.find_element_by_id("passwd-id")
獲取name標簽值
element = driver.find_element_by_name("user-name")
獲取標簽名值
element = driver.find_elements_by_tag_name("input")
也可以通過XPath來匹配
element = driver.find_element_by_xpath("http://input[@id='passwd-id']")
定位UI元素 (WebElements)
關于元素的選取,有如下的API 單個元素選取
find_element_by_id
find_elements_by_name
find_elements_by_xpath
find_elements_by_link_text
find_elements_by_partial_link_text
find_elements_by_tag_name
find_elements_by_class_name
find_elements_by_css_selector
By ID
假設有一個div的,他的id為coolestWidgetEvah,我們可以通過下面的方式來找到這個div
<div id="coolestWidgetEvah">...</div>
方式一:
element = driver.find_element_by_id("coolestWidgetEvah")
方式二:倒入相關模塊
from selenium.webdriver.common.by import By
##### 使用如下
element = driver.find_element(by=By.ID, value="coolestWidgetEvah")
By Class Name
<div class="cheese"><span>Cheddar</span></div><div class="cheese"><span>Gouda</span></div>
實現
cheeses = driver.find_elements_by_class_name("cheese")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
cheeses = driver.find_elements(By.CLASS_NAME, "cheese")
By Tag Name
<iframe src="..."></iframe>
實現
frame = driver.find_element_by_tag_name("iframe")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
frame = driver.find_element(By.TAG_NAME, "iframe")
By Name
<input name="cheese" type="text"/>
實現
cheese = driver.find_element_by_name("cheese")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.NAME, "cheese")
By Link Text
<a >下一頁</a>
實現
cheese = driver.find_element_by_link_text("下一頁")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.LINK_TEXT, "下一頁")
By Partial Link Text
通過局部的Link Text實現查找
<a >search for cheese</a>
實現
cheese = driver.find_element_by_partial_link_text("cheese")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.PARTIAL_LINK_TEXT, "cheese")
By CSS
<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>
實現
cheese = driver.find_element_by_css_selector("#food span.dairy.aged")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
cheese = driver.find_element(By.CSS_SELECTOR, "#food span.dairy.aged")
By XPath
<input type="text" name="example" />
<input type="text" name="other" />
inputs = driver.find_elements_by_xpath("http://input")
------------------------ or -------------------------
from selenium.webdriver.common.by import By
inputs = driver.find_elements(By.XPATH, "http://input")
頁面前進和后退
操作頁面的前進和后退功能:
driver.forward() #前進
driver.back() # 后退
Cookies
獲取頁面每個Cookies值,用法如下
cookies = driver.get_cookies()
for cookie in cookies:
print("%s -> %s" % (cookie['name'], cookie['value']))
cookie_dict = {i['name']:i['value'] for i in cookies}
print(cookie_dict)
添加cookies
driver.add_cookie(cookie_dict)
刪除Cookies,用法如下
- 刪除一個特定的cookie
driver.delete_cookie("CookieName")
- 刪除所有cookie
driver.delete_all_cookies()
設置無頭瀏覽器
opt = webdriver.ChromeOptions()
opt.set_headless()
設置代理
opt = webdriver.ChromeOptions()
opt.add_argument("--proxy-server=http://118.20.16.82:9999")
一定要注意,=兩邊不能有空格
鼠標動作鏈
有些時候,我們需要再頁面上模擬一些鼠標操作,比如雙擊、右擊、拖拽甚至按住不動等,我們可以通過導入 ActionChains 類來做到:
#-*- coding:UTF-8 -*-
##### 導入ActionChains類
from selenium.webdriver import ActionChains
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome(executable_path='/Users/ljh/Desktop/chromedriver')
driver.get('http://www.baidu.com')
##### 鼠標移動到ac位置,移動到第四個a標簽的位置
action = driver.find_element_by_xpath('//div[@id="u1"]/a[4]')
ActionChains(driver).move_to_element(action).perform()
##### 在action上單擊
ActionChains(driver).move_to_element(action).click(action).perform()
##### 在 ac 位置雙擊
ActionChains(driver).move_to_element(action).double_click(action).perform()
##### 在 ac 位置右擊
ActionChains(driver).move_to_element(action).context_click(action).perform()
##### 在 ac 位置左鍵單擊hold住
ActionChains(driver).move_to_element(action).click_and_hold(action).perform()
##### 將 ac1 拖拽到 ac2 位置
time.sleep(5)
ac1 = driver.find_element_by_id("su")
ac2 = driver.find_element_by_class_name('mnav')
ActionChains(driver).drag_and_drop(ac1,ac2).perform()
time.sleep(5)
driver.quit()
彈窗處理
當你觸發了某個事件之后,頁面出現了彈窗提示,處理這個提示或者獲取提示信息方法如下:
alert = driver.switch_to_alert()
(選項卡管理)頁面切換
一個瀏覽器肯定會有很多窗口,所以我們肯定要有方法來實現窗口的切換。切換窗口的方法如下:
js = 'window.open("http://www.baidu.com/")'
driver.execute_script(js)
driver.switch_to.window(driver.window_handles[0])
也可以使用 window_handles 方法來獲取每個窗口的操作對象。例如:
for handle in driver.window_handles:
driver.switch_to_window(handle)
切換Frame
網頁中有一種節點叫做iframe,也就是子Frame,我們不能夠直接獲取到子Frame中的節點,要想獲取到需要切換到子frame下
login_frame:為子frame的名稱
driver.switch_to_frame('login_frame')
頁面等待
注意:這是非常重要的一部分!! 現在的網頁越來越多采用了 Ajax 技術,這樣程序便不能確定何時某個元素完全加載出來了。如果實際頁面等待時間過長導致某個dom元素還沒出來,但是你的代碼直接使用了這個WebElement,那么就會拋出NullPointer的異常。 為了避免這種元素定位困難而且會提高產生 ElementNotVisibleException 的概率。所以 Selenium 提供了兩種等待方式,一種是隱式等待,一種是顯式等待。
隱式等待是等待特定的時間,顯式等待是指定某一條件直到這個條件成立時繼續執行。
隱式等待
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(10) # seconds
driver.get("http://www.xxxxx.com/loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")
顯式等待
顯式等待指定某個條件,然后設置最長等待時間。如果在這個時間還沒有找到元素,那么便會拋出異常了。 程序默認會 0.5s 調用一次來查看元素是否已經生成,如果本來元素就是存在的,那么會立即返回。
from selenium import webdriver
from selenium.webdriver.common.by import By
# WebDriverWait 庫,負責循環等待
from selenium.webdriver.support.ui import WebDriverWait
# expected_conditions 類,負責條件出發
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("http://www.xxxxx.com/loading")
try:
##### 會在這里等待,如果10秒內 id="myDynamicElement"的標簽出現
則返回,如果不出現則報異常
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.ID, "myDynamicElement")
)
)
finally:
driver.quit()
下面是一些內置的等待條件,你可以直接調用這些條件,而不用自己寫某些等待條件了。
title_is 標題是某內容
title_contains 標題包含某內容
presence_of_element_located 確保節點在本地加載出來傳入元組(By.ID,'password')
visibility_of_element_located 節點可見,傳入定位元組
presence_of_all_elements_located 所有節點加載出來
text_to_be_present_in_element 某個節點的文本包含某文字
text_to_be_present_in_element_value 某個節點的值包含某文字
frame_to_be_available_and_switch_to_it 加載并切換
invisibility_of_element_located 節點不可見
element_to_be_clickable – 節點可點擊.
staleness_of 判斷某個節點是否在文本中
element_located_to_be_selected 節點可選擇,傳入定位元組
alert_is_present 是否出現警告
https://www.cnblogs.com/peng-lan/p/9604672.html
異常處理
- 請求超時異常處理
from selenium.common.exceptions import TimeoutException
try:
brower.get(url)
except TimeoutException:
print('Time out')
- 找不到標簽的異常處理
from selenium.common.exceptions import NoSuchElementException
try:
brower.find_element_by_id('').click()
print('有標簽')
except NoSuchElementException:
print('沒有這個標簽')