我正在尝试从此html代码段中获取文本“ <1小时”。
<div class="details_wrapper">
<div class="detail">
<b>Recommended length of visit:</b>
<1 hour
</div>
<div class="detail">
<b>Fee:</b>
No
</div>
</div>
这是我正在使用的xpath表达式:
visit_length = response.xpath(
"//div[@class='details_wrapper']/"
"div[@class='detail']/b[contains(text(), "
"'Recommended length of visit:')]/parent::div/text()"
).extract()
但是它无法获取文本。我认为这是由于我需要的文本中的“ <”,它被认为是html标记。我如何刮擦文本“ <1小时”?
考虑到Scrapylxml
在后台使用,可能值得检查一下如何lxml
处理这种HTML,它<
在一个文本节点中包含XML特殊字符:
>>> from lxml import html
>>> raw = '''<div class="details_wrapper">
... <div class="detail">
... <b>Recommended length of visit:</b>
... <1 hour
... </div>
... <div class="detail">
... <b>Fee:</b>
... No
... </div>
... </div>'''
...
>>> root = html.fromstring(raw)
>>> print html.tostring(root)
<div class="details_wrapper">
<div class="detail">
<b>Recommended length of visit:</b>
<div class="detail">
<b>Fee:</b>
No
</div>
</div></div>
请注意,在上面的演示中,您怀疑文本节点'<1 hour'
已完全脱离root
元素源。作为一种解决方法,请考虑使用,BeautifulSoup
因为在处理这种HTML情况下它更加合理(您可以通过response.body_as_unicode()
创建soup
from Scrapy响应来传递):
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(raw, "html.parser")
>>> print soup.prettify()
<div class="details_wrapper">
<div class="detail">
<b>
Recommended length of visit:
</b>
<1 hour
</div>
<div class="detail">
<b>
Fee:
</b>
No
</div>
</div>
可以使用BS查找目标文本节点,如下所示:
>>> soup.find('b', text='Recommended length of visit:').next_sibling
u'\n <1 hour\n'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句