Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Selenium Python: หา Element และดึง Text

ใช้ Selenium WebDriver หา element และดึงข้อความ (text) ได้ โดยระบุ locator (id, class, css selector, xpath) แล้วใช้ property .text

Syntax

text = driver.find_element_by_css_selector("h4").text
  • driver = WebDriver object
  • find_element_by_css_selector = หา element ด้วย CSS selector
  • .text = ดึงข้อความภายใน element

ตัวอย่างโค้ด

from selenium import webdriver

driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/index.htm")

# หา element h4 และดึง text
s = driver.find_element_by_css_selector("h4").text
print("The text is: " + s)

driver.quit()

ผลลัพธ์

The text is: You are browsing the best resource for Online Education

Locator Types ที่ใช้ได้

Methodคำอธิบาย
find_element_by_idหาด้วย attribute id
find_element_by_nameหาด้วย attribute name
find_element_by_class_nameหาด้วย class
find_element_by_css_selectorหาด้วย CSS selector (แนะนำ)
find_element_by_xpathหาด้วย XPath
find_element_by_tag_nameหาด้วย HTML tag
find_element_by_link_textหา link ด้วยข้อความเต็ม
find_element_by_partial_link_textหา link ด้วยข้อความบางส่วน
หมายเหตุ: Selenium 4 แนะนำให้ใช้ find_element(By.CSS_SELECTOR, "h4") แทนเมธอดเก่า