【问题标题】:Downloading PDF documents using Scrapy [duplicate]使用 Scrapy 下载 PDF 文档 [重复]
【发布时间】:2020-02-01 08:55:37
【问题描述】:

我正在尝试使用用 scrapy 编写的蜘蛛下载 pdf 文档。我能够在页面上获取我需要的所有文档,但它们不是保存为 pdf 文件,而是保存为编码的文本文件。

我正在下载的 href 标签看起来像这样

<a href="/utils/view?id=37a074754f8d7d7302e0a32d9b049054" target="_blank" title="Download/View Attachment_1_PandemicFlu.pdf" class="file" id="yui-gen6">Attachment_1_Pandemi...</a>

相对网址指向https://www.fbo.gov/utils/view?id=37a074754f8d7d7302e0a32d9b049054

似乎问题在于href链接中没有.pdf。我试图在我的程序(和浏览器)中附加后缀,但该链接不存在,也没有下载任何内容。

任何帮助将不胜感激!

我的代码在下面

import scrapy
from scrapy.loader import ItemLoader
from FBOSpider.items import FbospiderItem

class fbo_spider(scrapy.Spider):
    name = "fbospider"

    start_urls = ["https://www.fbo.gov/spg/AOC/AOCPD/WashingtonDC/RFPPPA190087/listing.html"]

    def parse(self, response):
        base_url = "https://www.fbo.gov"
        for link in response.xpath("//*[@class='pkglist']/dd/a"):
            loader = ItemLoader(item= FbospiderItem(), selector=link)
            relative_url = link.xpath(".//@href").extract_first()
            absolute_url = base_url + relative_url # this is where I tried to add: + '.pdf'
            loader.add_value('file_urls', absolute_url)
            yield loader.load_item()

更新:在下面的答案的帮助下得到了它。这是我的解决方案。希望对您有所帮助。

import scrapy
import requests

class fbo_spider(scrapy.Spider):
    name = "fbospider"

    start_urls = ["https://www.fbo.gov/spg/AOC/AOCPD/WashingtonDC/RFPPPA190087/listing.html"]

    def parse(self, response):

        base_url = "https://www.fbo.gov" # base url used build url from href link
        i = 1

        # xpath to retrieve the part of html which holds documents
        for link in response.xpath("//*[@class='pkglist']/dd/a"):
            relative_url = link.xpath(".//@href").extract_first()

            # ex: https://www.fbo.gov/utils/view?id=921ca3f6f2ae471ab579075b8dc37afb
            absolute_url = base_url + relative_url 

            # request to fetch pdf documents using absolute url
            r = requests.get(absolute_url)
            with open("file%s.pdf" % i, 'wb') as f:
                f.write(r.content)
            i+=1

【问题讨论】:

  • @Vishnudev 在该示例中,程序查找“.pdf” - 我的问题是链接没有该扩展名

标签: python pdf web-scraping scrapy downloadfile


【解决方案1】:

使用 requests 库获取文件

import requests

def download(url):
    print('Beginning file download with requests')

    r = requests.get(url)

    with open('some_name.pdf', 'wb') as f:
        f.write(r.content)

    # Retrieve HTTP meta-data
    print(r.status_code)
    print(r.headers['content-type'])
    print(r.encoding)

download('https://www.fbo.gov/utils/view?id=37a074754f8d7d7302e0a32d9b049054')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    相关资源
    最近更新 更多