Python:Scrapy 返回所有 html 个后续元素,而不仅仅是 html 个元素

Python: Scrapy returning all html following element instead of just html of element

我遇到了 Scrapy 行为异常的问题。

我几个月前写了一个简单的函数,returns 给定 xpath 中的项目列表。

def get_html(response,path):
    sel = Selector(text = response.page_source)
    time.sleep(.2)
    items = sel.xpath(path).getall()
    return items

用法示例:

<body>
    <div id="1">Some Text</div>
    <div id="2">Different Text</div>
    <a href="#">Some link</a>
</body>

如果我想获得所有 div 个元素,我会这样写:

get_html(response,'//div')

我期待并且之前收到过此输出

['<div id="1">Some Text</div>',
 '<div id="2">Different Text</div>']

但是,现在当我调用这个方法时,我收到这个输出

['<div id="1">Some Text</div><div id="2">Different Text</div><a href="#">Some link</a></body>',
 '<div id="2">Different Text</div><a href="#">Some link</a></body>']

问题不是因为我抓取的网页发生了变化,我在最初抓取时保存了源代码,它与我今天在网页上看到的源代码相同。这个问题存在于我试图抓取的多个网站上。我不确定问题是什么,或者如何解决。我要么需要解决问题,要么用另一个行为相同的函数替换该函数。

我知道有一些方法可以拆分字符串并删除不需要的数据,但是我已经在 100 多个模块中使用了这个函数,并且不想冒险通过硬编码这样的解决方案来破坏它们。我需要了解为什么函数的输出发生了变化,尽管源代码没有任何变化。

编辑:

根据下面的评论,这正是我在控制台中输入的内容以产生此结果。如果其他人无法重现,请告诉我如何开始诊断为什么会发生这种情况。我正在使用 Spyder 版本 4.2.5,Python 3.8.5,Scrapy 2.4.1.

In[1]: from scrapy.selector import Selector

In[2]: text = """<body>
        <div id="1">Some Text</div>
        <div id="2">Different Text</div>
        <a href="#">Some link</a>
    </body>"""

In[3]: sel = Selector(text=text)

In[4]: items = sel.xpath('//div').getall()

In[5]: items
Out[5]: 
['<div id="1">Some Text</div>\n        <div id="2">Different Text</div>\n        <a href="#">Some link</a>\n    </body></html>\n',
 '<div id="2">Different Text</div>\n        <a href="#">Some link</a>\n    </body></html>\n']

问题似乎在全新安装 Anaconda 后得到解决。不确定是什么导致它首先出现,希望它不会再次发生。

我在使用 MacOS、Anaconda、Python 3.7 和 Scrapy 2.4.1 时遇到了类似的问题。我发现使用 Python 3.9 和 Scrapy 2.5.0 创建一个新的 Conda 环境解决了这个问题。