使用scrapy刮取没有javascript代码的文本

发布于 2021-01-29 16:52:39

我目前正在使用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),但无济于事。

关注者
0
被浏览
46
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    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', )))
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看