[英]Unable to print the text using Python Selenium?
所以我想通過 XPath 從這個 HTML 打印出“ou”。
<div class="syllable">ou</div>
這是我的代碼:
elem = driver.find_elements_by_xpath('*my xpath*')
for my_elem in elem:
print(my_elem.text)
我在此代碼中使用了.text
,但它在運行時什么也沒有打印出來。 它應該打印ou
但它根本不打印任何東西。 如果有人可以告訴我我做錯了什么,那就太好了。
要打印文本, ou
可以使用以下任一定位器策略:
使用css_selector
和get_attribute("innerHTML")
:
print(driver.find_element_by_css_selector("div.syllable").get_attribute("innerHTML"))
使用xpath
和文本屬性:
print(driver.find_element_by_xpath("//div[@class='syllable']").text)
理想情況下,您需要為visibility_of_element_located()
引入WebDriverWait ,並且您可以使用以下任一Locator Strategies :
使用CSS_SELECTOR
和text屬性:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.syllable"))).text)
使用XPATH
和get_attribute()
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='syllable']"))).get_attribute("innerHTML"))
控制台 Output:
ou
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
鏈接到有用的文檔:
get_attribute()
方法Gets the given attribute or property of the element.
text
屬性返回The text of the element.
如果您無法使用 .text 打印文本,則使用 .get_attribute("innerHTML") 這將挑釁地打印出文本。
例如。 你的代碼應該是這樣的
elem = driver.find_elements_by_xpath('*my xpath*').get_attribute("innerHTML")
for my_elem in elem:
print(my_elem)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.