python - 使用scrapy按扩展类型保存网页上的文件

标签 python web-scraping scrapy

我是 Python 的新手,我正在尝试使用 scrapy 下载并保存此网站中的 pdf 文件: http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard

以下是我的代码:

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector


class legco(BaseSpider):
  name = "legco"
  allowed_domains = ["http://www.legco.gov.hk/"]
  start_urls = ["http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard"]
  rules =(
    Rule(SgmlLinkExtractor(allow=r"\.pdf"), callback="save_pdf")
          )

def parse_listing(self, response):
    hxs = HtmlXPathSelector(response)
    pdf_urls=hxs.select("a/@href").extract()
    for url in pdf_urls:
        yield Request(url, callback=self.save_pdf)

def save_pdf(self, response):
    path = self.get_path(response.url)
    with open(path, "wb") as f:
        f.write(response.body)

基本上,我试图将搜索限制为仅包含“.pdf”的链接,然后按“a/@hfref”进行选择。

从输出中,我看到这个错误:

2015-03-09 11:00:22-0700 [legco] ERROR: Spider error processing http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard>

谁能告诉我如何修复我的代码?非常感谢!

最佳答案

首先,您需要使用 CrawlSpider 如果你想要 rules上类。此外,rules应该定义为一个可迭代对象,通常它是一个元组(缺少一个逗号)。

无论如何,我不会采用这种方法,而是使用普通的 BaseSpider , 遍历链接并检查 href.pdf 结尾,然后,在回调中,将 pdf 保存到文件中:

import urlparse

from scrapy.http import Request
from scrapy.spider import BaseSpider


class legco(BaseSpider):
    name = "legco"

    allowed_domains = ["www.legco.gov.hk"]
    start_urls = ["http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/mtg_0708.htm#hansard"]

    def parse(self, response):
        base_url = 'http://www.legco.gov.hk/general/chinese/counmtg/yr04-08/'
        for a in response.xpath('//a[@href]/@href'):
            link = a.extract()
            if link.endswith('.pdf'):
                link = urlparse.urljoin(base_url, link)
                yield Request(link, callback=self.save_pdf)

    def save_pdf(self, response):
        path = response.url.split('/')[-1]
        with open(path, 'wb') as f:
            f.write(response.body)

(为我工作)

关于python - 使用scrapy按扩展类型保存网页上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28948800/

相关文章:

python - 从 Pipeline 调用 Spider 的方法 - Python Scrapy

css - Scrapy 无法通过 CSS 或 xPath 请求文本

python - 将 2.x 代码移植到 3.x 时出现 tkinter 问题, 'tkinter' 模块属性不存在

python3 : Unescape unicode escapes surrounded by unescaped characters

python - 在特定文本之后和特定文本之前刮取文本

python - 无法以正确的方式使用 "explicit wait"

Python (2.*) Tkinter - 高级事件处理格式

python - col 函数如何知道我们引用的是哪个 DataFrame?

python - 如何访问 newspaper3k 中的缓存文章

python - 如何从 python 中的字符串中删除 "🇺🇸"?