selenium是python的非標準庫,使用時需要下載安裝
安裝命令 pip install selenium
selenium是python的自動化測驗模塊,可以模擬瀏覽器的行為
所以在使用之前還要安裝瀏覽器驅動,不同的版本對應不同的驅動檔案,這里就不一一贅述了,網上相關的介紹有很多(主要是作者懶)
下載后將驅動檔案放到添加過環境變數的路徑,以便系統在使用時找到它,這里我把它放在了python的安裝目錄里
前戲部分就做完了,可以開始了
from selenium import webdriver
import time
# 創建Chrome物件
driver = webdriver.Chrome()
# 打開瀏覽器預設網址
driver.get('https://www.baidu.com')
# 通過id獲取搜索框
input_ele = driver.find_element_by_css_selector('#kw')
# 模擬鍵盤操作 輸入框輸入內容
input_ele.send_keys("虞書欣")
# 模擬滑鼠點擊操作
driver.find_element_by_css_selector('#su').click()
# 延遲2秒,等待頁面重繪完成
time.sleep(2)

a_ele = driver.find_element_by_css_selector('#content_left div.c-container a') # 決議頁面元素 定位到目標鏈接
'''
中間遇到一個問題
使用id = 1定位時定位不到該節點,
a_ele = driver.find_element_by_css_selector('#content_left div#1 a')
報錯:
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
開始想的時頁面可能這個元素還沒重繪完成,后來我頁面延遲5秒后還是報錯
然后我使用class定位,成功定位到該節點,然后獲取該節點的id,輸出為:1
還是沒搞懂為什么不能使用id定位到該節點,不知哪位大撈可以幫忙解讀解讀
原因是id為數字不符合python的命名規則......
'''
結合實體總結一下:
driver.find_element_by_css_selector('#content') 查找id為content的節點
driver.find_element_by_css_selector('.content') 查找class為content的節點
driver.find_element_by_css_selector('div#conten>a')
查找id為content的div的所有子節點為a標簽的節點
driver.find_element_by_css_selector('div#conten a')
查找id為content的div的所有子孫節點為a標簽的節點
driver.find_element_by_css_selector('#conten p:nth-child(2)')
查找id為content的節點中的其父元素的第二個子元素是p標簽的節點,并不是指第二個p標簽節點
driver.find_element_by_css_selector('#conten>p:nth-of-type(2)')
查找id為content的節點的第二個p標簽節點
driver.find_element_by_css_selector('.content[name=value]')
查找class為content且name屬性為value的所有節點
find_element_by_css_selector 回傳匹配到的第一個節點
find_elements_by_css_selector 回傳匹配到的所有節點,型別是list
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/158671.html
標籤:Python
上一篇:Python3標準庫:json JavaScript物件記法
下一篇:python序列(十)字典
