【发布时间】: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 <newline> Wibble school of Wobble <newline><newline>12th Hurr Durr Street, 12345 Derp <newline> Phone: 123 567 890 <newline> Fax: 666 69 69 69整个地址 - 我想尽可能地分离这些数据,所以它不满足我 -
@WiktorPrzybylski 此时使用 regex 或 python 字符串函数从返回的字符串中删除您想要的内容可能更容易。我经历过类似的催泪页面结构,所以我能感受到你的痛苦。
-
是的,我第二个@cssko,最好使用正则表达式并剥离字符串。
-
例如,如果
foo是您的字符串,那么:string.split(foo, '\n')将为您提供由'\n' 划分的字符串列表。
标签: python html selenium selenium-webdriver