首页 > 解决方案 > 为什么scrapy Xpath 找不到我的浏览器Xpath 找到的内容?

问题描述

我想通过 Xpath 在页面中找到一些东西(Scrapy 的第一个项目),例如页面https://github.com/rg3/youtube-dl/pull/11272

在我的 Opera inspect 和 firefox TryXpath插件中,这个 Xpath 表达式具有相同的结果:

//div[@class='文件 js-comment-container js-resolvable-timeline-thread-container has-inline-notes']

它是这样的:

在此处输入图像描述

但是在 Scrapy 1.6 Xpath 中,当我想得到它的结果时,它没有找到任何东西,只是返回一个空列表

 def parse(self, response):
    print(response.xpath('''//div[@class='file js-comment-container js-resolvable-timeline-thread-container has-inline-notes']'''))

结果就是[]

你认为是什么问题?我该如何解决?提前致谢。

注意:是的,我知道robots.text甚至ROBOTSTXT_OBEY = False

标签: pythonxpathscrapyweb-crawler

解决方案


似乎其中一些类是由 javascript 添加的。
但是,如果您能够找到合适的选择器,即使未执行 javascript,您仍然可以选择您尝试定位的 div:

>>> fetch('https://github.com/rg3/youtube-dl/pull/11272')
2019-02-09 14:50:19 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://github.com/rg3/youtube-dl/pull/11272> (refere
r: None)
>>> response.css('div.file')
[<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' file ')]" dat
a='<div class="file js-comment-container js'>, <Selector xpath="descendant-or-self::div[@class and contains(concat(' ',
normalize-space(@class), ' '), ' file ')]" data='<div class="file js-comment-container js'>, <Selector xpath="descendant
-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' file ')]" data='<div class="file js-comme
nt-container js'>, <Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '
), ' file ')]" data='<div class="file js-comment-container js'>, <Selector xpath="descendant-or-self::div[@class and con
tains(concat(' ', normalize-space(@class), ' '), ' file ')]" data='<div class="file js-comment-container js'>, <Selector
 xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' file ')]" data='<div cl
ass="file js-comment-container js'>, <Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-
space(@class), ' '), ' file ')]" data='<div class="file js-comment-container js'>, <Selector xpath="descendant-or-self::
div[@class and contains(concat(' ', normalize-space(@class), ' '), ' file ')]" data='<div class="file js-comment-contain
er js'>, <Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' file
')]" data='<div class="file js-comment-container js'>]
>>> len(_)
9

推荐阅读