使用 Selenium 和 Python 查詢元素和文字?
我們可以使用 Selenium webdriver 查詢元素及其文字。首先,我們必須使用 id、classname、css 等定位器來識別元素。然後,要獲取文字,我們必須藉助text 方法。
語法
s = driver.find_element_by_css_selector("h4").text
此處,driver 是 webdriver 物件。find_element_by_css_selector 方法用於使用 css 定位器型別識別元素,並且定位器值作為引數傳遞給該方法。最後,使用text 方法來獲取元素的文字內容。
讓我們看一看具有文字內容的元素的 html。輸出應該是您正在瀏覽線上教育的最佳資源。
示例
程式碼實現。
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe" # implicit wait applied driver.implicitly_wait(0.5) driver.get("https://tutorialspoint.tw/index.htm") # to identify element and obtain text s = driver.find_element_by_css_selector("h4").text print("The text is: " + s)
輸出
廣告