天天看點

從0學爬蟲-selenium

selenium是一個web的自動化測試工具,它支援所有主流的浏覽器,可以接收指令,讓浏覽器自動加載頁面

1.首先需要安裝chromedriver驅動。

chromedriver是一個驅動Chrome浏覽器的驅動程式,先下載下傳驅動

下載下傳位址:http://chromedriver.storage.googleapis.com/index.html

找到自己Chrome對應的版本,将解壓後的chromedriver.exe檔案放到python的根目錄下即可。

2.敲代碼

注意:selenium4.x的文法與老版本略有不同,我的是4.1.0

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# 執行個體化浏覽器
driver = webdriver.Chrome() 
# 發送請求
url = 'https://www.baidu.com/'
driver.get(url)
# 頁面的最大化
driver.maximize_window() 
# 頁面操作
driver.page_source      # 頁面源碼
driver.get_cookies()    # 擷取cookie
driver.current_url      # 目前請求的URL位址
driver.back() #後退
driver.forward() # 前進
driver.save_screenshot('img.png') # 頁面截圖,另存為img.png

# 定位元素,可以根據ID定位,也可以根據class_name定位,也可以使用xpath文法
driver.find_element(By.ID,'su')
driver.find_element(By.CLASS_NAME,'su')
driver.find_element(By.XPATH,'//div')
# 操作
driver.find_element(By.ID,"kw").send_keys("長城") # 輸入長城
driver.find_element(By.ID,"su").click() # 點選
# 要注意,想要擷取所有滿足條件的元素,需要用find_elements。           

行為鍊

#前略
# 定位百度的輸入框
input = driver.find_element(By.ID,"kw")
# 定位百度按鈕
btntag = driver.find_element(By.ID,"su").click()
# 執行個體化行為鍊
actions = ActionChains(driver)
# 在定位好的輸入框輸入内容
actions.send_keys_to_element(input,'python')
# 點選
actions.move_to_element(btntag)
actions.click()
# 執行所有存儲的操作。
actions.perform()           

頁面等待,等待元素

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("https://www.baidu.com/")

wait = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "su"))
 )           

其他的等待條件

  • presence_of_element_located:某個元素已經加載完畢了。
  • presence_of_all_elements_located:網頁中所有滿足條件的元素都加載完畢了。
  • element_to_be_clickable:某個元素是可以點選了。

去除識别

from selenium.webdriver import ChromeOptions
# 去除識别
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=option)
driver.get('https://www.baidu.com/')
# 特征識别
script = 'Object.defineProperty(navigator, "webdriver", {get: () => false,});'
driver.execute_script(script)           

繼續閱讀