python3使用selenium + Chrome基礎操作代碼


selenium是Python的第三方庫,使用前需要安裝。但是如果你使用的是anaconda,就可以省略這個步驟,為啥?自帶,任性。

安裝命令:

pip install selenium

(一)使用selenium打開指定網站,這里以淘寶為例。

# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 10:12:39 2018
@author: brave_man
email: 1979887709@qq.com
"""

from selenium import webdriver
from time import sleep

b = webdriver.Chrome()
b.get("http://www.taobao.com")

elem = b.find_element_by_id('q')
elem.send_keys('iphone')
sleep(3)
elem.clear()
elem.send_keys("ipad")
button = b.find_element_by_class_name("btn-search")
button.click()
sleep(5)
b.close()

(二)簡單的拖拽動作(用於驗證碼識別)

# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 15:00:10 2018
@author: brave_man
email: 1979887709@qq.com
"""

from selenium import webdriver
from selenium.webdriver import ActionChains

b = webdriver.Chrome()
url = "http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
b.get(url)
b.switch_to.frame('iframeResult')
sou = b.find_element_by_css_selector('#draggable')
tar = b.find_element_by_css_selector('#droppable')
actions = ActionChains(b)
actions.drag_and_drop(sou, tar)
actions.perform()

(三)在爬蟲中,可能會由於網速等外界因素的影響,造成獲取網頁元素失敗,這里介紹兩種等待模式

1.  隱式等待:webdriver沒有在DOM中找到想要的元素,在等待指定的時間后,會拋出一個找不到指定元素的異常。在網速特別慢的情況可以使用

from selenium import webdriver

b = webdriver.Chrome()
b.implicitly_wait(10)
b.get("https://www.zhihu.com/explore")
elem = b.find_element_by_class_name('zu-top-add-question')
print(elem)

2. 顯式等待

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

b = webdriver.Chrome()
#b.implicitly_wait(10)
b.get("https://taobao.com/")
#elem = b.find_element_by_class_name('zu-top-add-question')
b_wait = WebDriverWait(b, 10)
elem = b_wait.until(EC.presence_of_all_elements_located((By.ID, 'q')))
button = b_wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.btn-search')))
print(elem, button)

(四)前進后退

from selenium import webdriver
from time import sleep

b = webdriver.Chrome()
b.get("http://www.baidu.com")
sleep(1)
b.get("http://www.sina.com.cn")
sleep(1)
b.back()
sleep(3)
b.forward()
sleep(3)
b.close()

更多內容可以參考文檔:http://selenium-python-zh.readthedocs.io/en/latest/index.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM