我目前正在使用scrapy设置一堆蜘蛛。这些蜘蛛应仅从目标站点中提取文本(文章,论坛帖子,段落等)。
问题是:有时,我的目标节点包含一个<script>
标记,因此抓取的文本包含javascript代码。
这是我正在使用的真实示例的链接。在这种情况下,我的目标节点是//td[@id='contenuStory']
。问题是<script>
第一个子div中有一个标签。
我花了很多时间在Web和SO上寻找解决方案,但是我什么也找不到。希望我不会错过任何显而易见的事情!
HTML响应(仅目标节点):
<div id="content">
<div id="part1">Some text</div>
<script>var s = 'javascript I don't want';</script>
<div id="part2">Some other text</div>
</div>
我想要的物品是什么:
Some text
Some other text
我得到的是:
Some text
var s = 'javascript I don't want';
Some other text
给定一个xpath选择器,我正在使用以下函数来提取文本:
def getText(hxs):
if len(hxs) > 0:
l = hxs.select('string(.)')
if len(l) > 0:
s = l[0].extract().encode('utf-8')
else:
s = hxs[0].extract().encode('utf-8')
return s
else:
return 0
我尝试使用XPath轴(类似child::script
),但无济于事。
从w3lib.html
以下位置尝试utils函数:
from w3lib.html import remove_tags, remove_tags_with_content
input = hxs.select('//div[@id="content"]').extract()
output = remove_tags(remove_tags_with_content(input, ('script', )))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句