简体   繁体   English

通过click()找到超链接后如何使用find_element

[英]how to use find_element after finding the hyperlink through click()

I used 我用了

continue_link=driver.find_elements_by_partial_link_text("contract")

to get a list of links. 获取链接列表。 How do I apply find_elements on web elements I got already? 如何在已有的Web元素上应用find_elements?

And how to return strings on web pages? 以及如何在网页上返回字符串? Can find_element do that? find_element可以做到吗?

For example: 例如:

      <div class="article-detail-text">
         <h1>notice</h1>
         <p class="article-date">release date:2019-05-22</p>

       <p>hi:<br />
  I like basketball and football.<br />
  I like cooking.<br />
  Thanks.</p>

And I want to return: "I like basketball and football. I like cooking. Thanks." 我想返回:“我喜欢篮球和橄榄球。我喜欢烹饪。谢谢。”

WebElement has find_elements() functions as well WebElement也具有find_elements()函数

continue_link = driver.find_elements_by_partial_link_text("contract")
for link in continue_link:
    elements = link.find_elements_by_partial_link_text('')

And to get specific substring you can do 并获得特定的子字符串,你可以做

s1 = 'I like basketball and football'
s2 = 'like'

result = s1[s1.index(s2) + len(s2):]

I believe the correct XPath expression to match the HTML snippet you provided would be something like: 我相信与您提供的HTML代码段相匹配的正确XPath表达式将类似于:

//div[@class='article-detail-text']/descendant::p[contains(text(),'hi')]

Once you locate the relevant <div> tag you will be able to get the text of the descendant <p> tag using innerText property 找到相关的<div>标记后,您将可以使用innerText属性获取后代 <p>标记的文本。

print(driver
      .find_element_by_xpath("//div[@class='article-detail-text']/descendant::p[contains(text(),'hi')]")
      .get_attribute("innerText"))

Demo: 演示:

在此处输入图片说明

To return the text I like basketball and football. I like cooking. Thanks. 要返回文字, I like basketball and football. I like cooking. Thanks. I like basketball and football. I like cooking. Thanks. You can try the following option. 您可以尝试以下选项。

print(' '.join(driver.find_element_by_xpath("//p[contains(.,'hi:')]").text.split('hi:')[1].splitlines()))

This will print : 这将打印:

I like basketball and football. I like cooking. Thanks.

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

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