【问题标题】:Scraping by Xpath in Scrapy在 Scrapy 中通过 Xpath 进行抓取
【发布时间】:2022-01-18 22:02:20
【问题描述】:

我想从网页上抓取文章(例如文章enter link description here)。我的代码应该抓取所有文章文本。我是通过 XPath 来做的。在开发工具中粘贴以下 XPath 后:(1.crtl+shift+i /// 2. ctrl+f)

//div[@class="item-page clearfix"]/*[self::p/text() or self::strong/text() or self::ol/text() or self::blockquote/text()]

它似乎可以工作并且能够找到所有文本。网页显示 XPath 工作正常。但我的 Python 和 Scrapy 不这么认为。 JSON 中的以下代码仅返回文章的第一段。我不明白为什么。为什么在网页上它可以工作而在 Python 中却不行?我错过了什么?

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from w3lib.html import remove_tags


class LubaczowSpider(CrawlSpider):
     name = 'Lubaczow'
     allowed_domains = ['zlubaczowa.pl']
     start_urls = ['http://zlubaczowa.pl/index.php/']

     rules = (
          Rule(LinkExtractor(restrict_xpaths="//p[@class='readmore']/a"), callback='parse', follow=True),)

     def parse(self, response):
          yield {
                "Text" :  response.xpath('normalize-space(//div[@class="item-page clearfix"]/*[self::p/text() or self::strong/text() or self::ol/text() or self::blockquote/text()])').getall(),
                "Url" : response.url       
             }

提前感谢您的建议和帮助!

【问题讨论】:

  • 请给出一个清晰的例子说明当前的结果和期望的结果。

标签: python-3.x web-scraping xpath scrapy


【解决方案1】:

当您在 xpath 版本 1 中使用 normalize-space(我相信它在 scrapy 中使用)时,任何尾随空格都会从字符串中删除,然后再返回 see mdn。这样做的效果是,彼此跟随的文本节点会将第一个节点之后的节点替换为空格,因此您只能返回第一段。

您可以尝试从子节点获取所有文本数据,然后将它们连接成一个字符串。请参阅下面的示例代码

from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from w3lib.html import remove_tags


class LubaczowSpider(CrawlSpider):
     name = 'Lubaczow'
     allowed_domains = ['zlubaczowa.pl']
     start_urls = ['http://zlubaczowa.pl/index.php/']

     rules = (
          Rule(LinkExtractor(restrict_xpaths="//p[@class='readmore']/a"), callback='parse', follow=True),)

     def parse(self, response):
          all_text = response.xpath("//div[@class='item-page clearfix']//child::text()").getall()
          text = ''.join([r.strip() for r in all_text]) # remove trailing spaces and combine into 1 string
          yield {
                "Text" :  text,
                "Url" : response.url       
             }

显示上述代码结果的示例截图如下所示

【讨论】:

  • 我只知道normalize-space函数
  • 抱歉,我还有一个问题。删除normalize-space 后,我的刮刀将页面上的所有文本返回给我。为什么?我在网页中的 XPath 没有显示评论部分。如果没有normalize-space 我没记错的话,就没有理由从评论部分获取文本。我的 XPath 似乎没有碰到 html 的那部分
  • 您的 xpath 正在选择所有 p 标记,它们是 div[@class='item-page clearfix'] 的子标记。当您通过右键单击并选择查看源(scrapy 看到的)来检查页面的源时,您会看到 cmets 文本位于 p 元素内,因此被您的 xpath 捕获
猜你喜欢
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多