【问题标题】:Why scrapy Xpath can not find what is found by my browser(s) Xpath?为什么scrapy Xpath 找不到我的浏览器Xpath 找到的内容?
【发布时间】:2019-02-09 12:22:41
【问题描述】:

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

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

//div[@class='file 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']'''))

结果就是[]

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

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

【问题讨论】:

  • 这些元素是由 JavaScript 动态生成的,所以不能从页面源中提取出来
  • @JaSON 很有趣!谢谢。有没有办法在python中提取它们?
  • @Peymanmohsenikiasari 你需要使用 Scrapy 和 Splash 来加载 Javascript。
  • @malberts 太好了,谢谢。

标签: python xpath scrapy web-crawler


【解决方案1】:

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

>>> 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    相关资源
    最近更新 更多