![](/img/trans.png)
[英]How to locate and click the element when the innerText contains leading and trailing white-space characters using Selenium and Python
[英]How to locate the element and extract the innerText using Selenium and Python
<span class="chr-UserDropdownItem-imageAndText">
<img class="chr-UserDropdownItem-image" src="/slm/profile/image/264023573852/24.sp?version=1" alt="User Profile Avatar">
<span class="smb-DropdownItem-text">
<span> test user </span>
</span>
</span>
通過查看上面的屏幕截圖,請幫助我從span 標簽中唯一地提取innerText
測試用戶。
要提取文本測試用戶,您必須為visibility_of_element_located()
引入WebDriverWait ,您可以使用以下任一定位器策略:
使用CSS_SELECTOR
和get_attribute()
:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.smb-DropdownItem-text>span"))).get_attribute("innerHTML"))
使用XPATH
和text屬性:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "span[@class='smb-DropdownItem-text']>span"))).text)
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以使用 xpath 找到該元素:
driver.find_element_by_xpath("//span[@class='smb-DropdownItem-text']//span[contains(text(),'test user')]");
您可以像這樣使用 XPath 來刪除空格:
driver.find_element_by_xpath('//span/text()[normalize-space()="test user"]')
如果 span 標簽中沒有空格,請以這種方式使用 XPath:
driver.find_element_by_xpath('//span[contains(text(), "test user")]')
對於動態:
driver.find_element_by_xpath('//span[contains(text(), "' . $HereIsSetYourDynamicallyVaribleName . '")]')
您可以嘗試使用以下 xpath。
//img[contains(@src, '/profile/image/')]]/following-sibling::span
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.