我遇到了一个我想废弃的页面 - 我在查看地址详细信息部分的结构时哭了很多次。但让我们具体一点:
我有这样的结果结构:
<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,它恰好包含所有信息。如何抓取这些东西?
最佳答案
您可以使用一段 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
关于Python、selenium 和在任何跨度或其他东西之外的 div 中捕获特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36717640/