【问题标题】:Python, selenium and catching specific text in div outside any span or somethingPython,硒和在任何跨度或其他东西之外的div中捕获特定文本
【发布时间】:2016-08-11 14:06:12
【问题描述】:

我遇到了一个我想废弃的页面 - 看着地址详细信息部分的结构,我哭了很多。但让我们具体一点:

我有这样的结果结构:

<div class="A">
  <div class="B">
    <div class="INFO">
      Foo Bar School of Baz and Qux
      <br>
      <span class="TYPE">
        Wibble school of Wobble
      </span>
      <br>
      <br>
      12th Hurr Durr Street, 12345 Derp
      <br>
      <span>Phone: 123 567 890 </span> <br>
      <span>Fax: 666 69 69 69 </span>
      <br>
    </div>
  </div>
</div>

我想在 python 中使用 selenium 提取地点的名称和地址。所以我写了 xpath 碰巧工作:

(//div[@class='INFO'])[1]//text()[not(parent::span) and normalize-space()]

但由于我要提取的东西不是元素,只是文本,它们是用 text() 指定的,带有“不要在跨度内”和“不要是空白”。

driver.find_element_by_xpath(thing_i_wrote_above)

抛出

mon.exceptions.InvalidSelectorException: Message: The given selector <the same xpath> is: [object Text]. It should be an element.

我看不到任何选择元素的方法,因为最接近的是 INFO,它恰好包含所有信息。这些东西怎么抢?

【问题讨论】:

  • 尝试使用此代码字符串driver.find_element_by_class_name('INFO').text 时会得到什么输出?
  • @andersson 我得到:Foo Bar School of Baz and Qux &lt;newline&gt; Wibble school of Wobble &lt;newline&gt;&lt;newline&gt;12th Hurr Durr Street, 12345 Derp &lt;newline&gt; Phone: 123 567 890 &lt;newline&gt; Fax: 666 69 69 69 整个地址 - 我想尽可能地分离这些数据,所以它不满足我
  • @WiktorPrzybylski 此时使用 regex 或 python 字符串函数从返回的字符串中删除您想要的内容可能更容易。我经历过类似的催泪页面结构,所以我能感受到你的痛苦。
  • 是的,我第二个@cssko,最好使用正则表达式并剥离字符串。
  • 例如,如果foo 是您的字符串,那么:string.split(foo, '\n') 将为您提供由'\n' 划分的字符串列表。

标签: python html selenium selenium-webdriver


【解决方案1】:

您可以使用一段 JavaScript 获取子文本节点:

# get the container
element = driver.find_element_by_css_selector(".INFO")

# return an array with the text from the children text nodes
texts = driver.execute_script("""
  return Array.from(arguments[0].childNodes)
    .filter(function(o){return o.nodeType === 3 && o.nodeValue.trim().length;})
    .map(function(o){return o.nodeValue.trim();})
  """, element)

print texts

您也可以使用 BeautifulSoup 来解析容器中的 html:

from bs4 import BeautifulSoup

# get the container
element = driver.find_element_by_css_selector(".INFO")

# parse the HTML from the container
bs = BeautifulSoup(element.get_attribute("outerHTML"))

# list all the children text nodes
texts = [v.strip() for v in bs.html.body.div.findAll(text=True, recursive=False) if v.strip()]

print texts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 2010-12-08
    • 2010-12-15
    • 2019-12-24
    • 2016-02-25
    相关资源
    最近更新 更多