ใช้ Selenium WebDriver หา element และดึงข้อความ (text) ได้ โดยระบุ locator (id, class, css selector, xpath) แล้วใช้ property .text
Syntax
text = driver.find_element_by_css_selector("h4").text
driver= WebDriver objectfind_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") แทนเมธอดเก่า