【问题标题】:Using Python & Selenium, how to extract the text from HTML containing the <p> tag?使用 Python 和 Selenium,如何从包含 <p> 标签的 HTML 中提取文本?
【发布时间】:2016-05-03 17:22:21
【问题描述】:

我知道这是一个非常简单的问题。我病得很重,试图完成这个演示文稿,但我的大脑似乎无法正常工作。

HTML代码如下:

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

缺陷是邮政编码文本字段仅接受四个字符。提交后,我试图在这种情况下获取数字“3502”并使用 len 来计算它们。

【问题讨论】:

    标签: python html python-3.x selenium


    【解决方案1】:

    问题是您无法在 selenium 中使用 find_element_* 命令直接定位“文本”节点 - 您使用的定位器必须指向实际元素。

    在这种情况下,我会得到 p 元素的文本,除以 : 并得到最后一项:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      相关资源
      最近更新 更多