简体   繁体   中英

Find a particular element of an html page using Selenium/Python

I have multiple levels of div class elements out of which I need to find just a particular elements and get the text value and store in a variable.

<div class="Serial">
<p> … </p>
<p>
<span>
    <a href="mailto:xyz@xyz.com">
        Mr. XYZ
    </a>
</span>
</p>
<p> … </p>
<p> … </p>

So, we have 4 different paragraphs out of which I need to only read second paragraph and save the email ID to a variable. When I use the following code,

find_element_by_xpath("//div[@class='Serial']")

I get all the 4 paragraph information. Is there anyway I can specify which paragraph to read within the div class? I know for sure the order doesn't change and I only want to read 2nd p element. Appreciate your help.

您可以通过将xpathfind_element_by_xpath("//div[@class='Serial']/p[2]/span/a")来尝试访问<p>标记,以访问第二段中显示的电子邮件ID。

I think this is not completely correct to rely on order of paragraphs - one day it may change, and those who will come after you can be slightly confused by p[2]. As you need to find text from paragraph with email link, I believe this XPath would do the trick:

//p[span/a[starts-with(@href, 'mailto:')]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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