繁体   English   中英

如何在一些文本之前将 XPath 写入文本?

[英]How to write XPath to text before some text?

我正在为我的 selenium 项目使用临时电子邮件,但我已经被这个问题困住了一段时间。 信息似乎总是在变化,我无法弄清楚我应该如何写它。 这是 HTML:

<a href="https://temp-mail.org/en/view/cd89ea25d93a2fed0d182d9d8225b5b" title="" class="viewLink title-subject" data-mail-id="cd89ea25d93a2fed0d182d9d82425b5b">812479 is your Instagram code</a>

我尝试使用我读过的各种方法来查找邮件 ID。

execute = browser.find_element_by_xpath('.//span[@class = "data-mail-id"]') #Attempt 1
execute = browser.find_element_by_xpath('//span[text()="Instagram"]')

我什至复制了完整的 xpath,但它总是返回Unable to Locate Element但是,每次向收件箱发送电子邮件时, data-mail-id和代码都会更改。 我需要改变什么?

我想要后跟" is your Instagram code"的字符串 ( "812479" )。

直接 XPath 1.0

这个 XPath 表达式,

substring-before(//a[contains(.,' is your Instagram code')][1], 
                 ' is your Instagram code')

将在第a包含该字符串a元素中返回' is your Instagram code'之前的子字符串,如果不存在此类元素,则返回空字符串。


Selenium 中的 XPath

您可以在 Selenium 中通过 XPath 选择a元素,

a = browser.find_element_by_xpath("//a[contains(.,' is your Instagram code')][1]")

然后通过a.text访问元素的文本使用split()实现substring-before() (链接显示after ,但技术很容易适应before )。

我非常喜欢使用 expected_conditions 来避免页面加载和脚本执行之间的时间问题。

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

myec = EC.visibility_of_element_located(
    (By.XPATH, '//a[contains(text(), "is your Instagram code")]'))

# search for the element on the page until found or TimeoutException is raised
wait = WebDriverWait(driver, timeout)
myelement = wait.until(myec, "Could not find Instagram Code") 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM