【问题标题】:Extracting information from anchor elements leading to pdf files从导致pdf文件的锚元素中提取信息
【发布时间】:2017-04-27 08:31:14
【问题描述】:

我正在使用Scrapy从网站抓取和抓取数据,主要由html页面和pdf文件组成(我修改了IGNORED_EXTENSIONS以允许抓取pdf)。

我需要提取被困在<a> 标签之间的文本:

<a href='some_document.pdf'>I need this text</a>

显然,我不能做 response.text 或 response.css,因为只有字节要读取(你会得到一个 AttributeError)。

我想到的一件事是爬取页面,从该页面中提取所有链接并将它们保存在文本文件中。它起作用了,除了我最终得到了很多重复的链接、损坏的链接(想想 403、404、500)或很多我不关心的链接。我想一定有更好的办法!

在阅读 Scrapy 文档时,我偶然发现了LxmlLinkExtractor 的文档。在 “constructor” 中,它有 2 个有趣的 字段:

  • tags (str or list) – 提取链接时要考虑的标签或标签列表。默认为 ('a', 'area')。
  • attrs (list) – 查找要提取的链接时应考虑的属性或属性列表(仅适用于 tags 参数中指定的那些标签)。默认为 ('href',)

这让我开始思考是否可以在抓取&lt;a&gt; 元素的属性值之前对其进行抓取。我对么?如果是,我如何在标签之间抓取文本?

源代码:

class ArchiveSpider(CrawlSpider):

...some code...

rules = [
        Rule(LinkExtractor(allow=[re.compile('pdf', re.IGNORECASE)]), 
                           callback='parse_pdf', 
                           follow=True),
        Rule(LinkExtractor(), callback='parse_item', follow=True)
    ]

    def parse_pdf(self, response):
        yield dict(url=response.url)

    def parse_item(self, response):
        if re.search(re.compile('pdf', re.IGNORECASE, response.headers.get('Content-Type').decode('utf-8')):
            parse_pdf(self, response)
        title = response.css('title::text').extract()[0].strip() if response.css('title::text') else ''
        yield dict(title=title, url=response.url)

【问题讨论】:

    标签: python html scrapy


    【解决方案1】:

    我不确定我是否理解正确,但你不能这样做:

    text = response.xpath('//a/text()').extract()
    

    您必须在 xpath 中指定所需的 &lt;a&gt; 元素,text() 选择标签之间的文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多