python - 为什么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
解决方案
似乎其中一些类是由 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
推荐阅读
- javascript - 如何在 Angular js 控制器中重构 10000 行代码?
- python - Python 3 中未初始化默认函数参数
- python - Python:将数组元素与浮点数进行比较,得到一个布尔列表
- c# - 列表及其所有嵌套列表值的 Linq 平均值
- php - Laravel:对多个图像进行图像验证不起作用
- dart - 如何在 Flutter 的 TextField 中添加遮罩?
- azure - 在 Azure 中基于 Web 发起创建 IaaS
- google-sheets - 基于 if/then 在多个字段上的条件格式
- wix - 使用自定义操作的 REG_MULTI_SZ 的 MsiSetProperty
- javascript - 以后是否可以将值绑定到函数中的 Vue 元素?