Python爬蟲利器—selenium
阿新 • • 發佈:2018-12-14
在學習爬蟲的時候,我接觸了selenium,發現其強大功能,可以模擬真實情況操縱瀏覽器,其實也是相當於一個第三方的包。
selenium十分好用 特別在面對一些有針對反爬蟲設計的網站時,能達到用時間換資料的效果
安裝
在控制檯下用PIP操作可以下載,不過在使用的時候要多下載一個webdriver的,我是用的是Chorme瀏覽器70版本,所以下載的是對應的chormedriver2.43版本,具體的對照關係可以參照chromedriver與鍍鉻對應的表關係這篇部落格。將webdriver的下載解壓並將其目錄放入環境變數路徑中後,就可以方便的使用硒了。下載地址可以去http://npm.taobao.org/mirrors/chromedriver/
操作
開啟瀏覽器並得到返回結果,在3秒後關閉
注意要用qiut()而不是靠近()不然有可能關閉不完全造成下一次開啟錯誤。
from selenium import webdriver #用來控制操作的時間 import time # selenium訪問頁面 # 建立瀏覽器物件 browser = webdriver.Chrome() # 發起請求 browser.get('https://www.taobao.com') # 獲取返回結果 #當前網址 print(browser.current_url) #網址內資源 print(browser.page_source) time.sleep(3) # 關閉瀏覽器 browser.quit()
獲取節點屬性
from selenium import webdriver import time browser = webdriver.Chrome() browser.get('https://www.zhihu.com/explore') logo = browser.find_element_by_id('zh-top-link-logo') print(logo) # 獲取節點屬性值 print(logo.get_attribute('class')) print(logo.get_attribute('href')) btn = browser.find_element_by_class_name('zu-top-search-button') # 獲取文字值 print(btn.text) time.sleep(5) browser.quit()
節點互動頁面操作
from selenium import webdriver
import time
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
# 節點互動
# 找到input輸入框
input_first = browser.find_element_by_id('q')
# 輸入要查詢的關鍵字
input_first.send_keys('小米')
time.sleep(2)
# 清空輸入框
input_first.clear()
input_first.send_keys('華為')
# 找到查詢按鈕
button = browser.find_element_by_class_name('btn-search')
# 點選查詢
button.click()
time.sleep(3)
browser.quit()
有些元素需要一段時間才會加載出來因此有隱式等待和顯式等待兩種方式
## 延時等待
#使用selenium去請求網頁獲取資源的時候,可能會有些ajax請求資源還沒有返回,這時候需要等待一段時間,等待頁面完全載入。
### 隱式等待
#使用隱式等待,如果瀏覽器沒有找到DOM節點,會等待一段時間,再去查詢節點,超出時間會丟擲異常。
from selenium import webdriver
browser = webdriver.Chrome()
# 隱式等待
browser.implicitly_wait(10)
browser.get('https://www.zhihu.com/explore')
logo = browser.find_element_by_id('zh-top-link-logo')
print(logo)
browser.quit()
### 顯式等待
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
browser.get('https://www.taobao.com')
# 建立一個wait物件,指定最長等待時間是10秒
wait = WebDriverWait(browser,10)
# expected_conditions EC是指的等待的條件物件
# presence_of_element_located 指等待指定節點加載出來
# element_to_be_clickable 指等待節點可點選
in_put = wait.until(EC.presence_of_element_located((By.ID,'q')))
btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'.btn-search')))
print(in_put.tag_name) # input
print(btn.tag_name) # button
browser.quit()