简体   繁体   中英

Using Python & Selenium, how to extract the text from HTML containing the <p> tag?

This I know is a very simple question. I'm quite sick and trying to finish up this presentation and my brain just doesn't seem to be working right.

The HTML code is as follows:

<p>
    <b>Postal code:</b>
    3502
</p>

The defect is the zipcode text field is only accepting four characters. Once submitted, I'm trying to grab the number "3502" in this case and use len to count them.

The problem is that you cannot directly locate the "text" nodes with find_element_* commands in selenium - the locators you use have to point to actual elements.

In this case, I would get the p element's text, split by : and get the last item:

text = driver.find_element_by_xpath("//p[b = 'Postal code:']").text
postal_code = text.split(":")[-1].strip()
print(postal_code)

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