【问题标题】:Scrapy: enabling files pipeline for absolute and relative paths?Scrapy:为绝对和相对路径启用文件管道?
【发布时间】:2018-02-04 18:37:42
【问题描述】:

问题:我的代码中缺少什么(请参阅下面的“当前代码”部分),使我能够使用 Scrapy 从绝对路径和相对路径下载文件?我很感激帮助。我对所有这些组件如何协同工作以及如何获得所需的行为感到迷茫。

背景:我结合了对 Scrapy 文档的研究、在 GitHub 上查找可比较的示例以及在 StackOverflow 上搜索答案,但我无法让 Scrapy 文件管道在其中工作我想要的方式。我正在查看具有大量文件(主要是 PDF 和 JPG)的相当基本的目标网站,这些文件在 a hrefimg src 下以绝对或相对路径的形式链接> 选择器。我想下载所有这些文件。我的理解是 response.follow 将遵循相对路径和绝对路径,但我不确定该函数是否总是会产生可以通过文件下载的路径管道。我想出了爬行绝对路径和相对路径,感谢my earlier question提供的答案。

遇到的问题:有两个主要问题。首先,我似乎无法让蜘蛛同时遵循绝对路径和相对路径。其次,我似乎无法获得文件管道来实际下载文件。这很可能是因为我不了解四个 .py 文件如何协同工作。如果有人可以提供一些基本的观察和指导,我相信我可以超越这个基本的 go/no-go 点,开始添加一些更复杂的功能。

当前代码:这里是myspider.py、items.py、pipelines.py和settings.py的相关内容。

myspider.py:注意,parse_items功能不完整,但我不明白是什么该功能应包括。

from scrapy import Spider
from ..items import MyspiderItem

# Using response.follow for different xpaths
class MySpider(Spider):
    name='myspider'
    allowed_domains=['example.com']
    start_urls=['http://www.example.com/']

    # Standard link extractor           
    def parse_all(self, response):
        # follow <a href> selector
        for href in response.xpath('//a/@href'):
            yield response.follow(href, self.parse_items)

        # follow <img src> selector
        for img in response.xpath('//img/@src'):
            yield response.follow(img, self.parse_items)

    # This is where I get lost
    def parse_items(self, response):
        # trying to define item for items pipeline
        MyspiderItem.item['file_urls']=[]

items.py

import scrapy

class MyspiderItem(scrapy.Item):
    file_urls=scrapy.Field()
    files=scrapy.Field()

settings.py:这是启用文件管道的相关部分。

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'scrapy.pipelines.files.FilesPipeline': 1}
FILES_STORE = '/home/me/Scraping/myspider/Downloads'

pipelines.py

class MyspiderPipeline(object):
    def process_item(self, item, spider):
        return item

【问题讨论】:

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


    【解决方案1】:

    我认为你的蜘蛛 myspider.py 出错了!

    def parse_all() 可能是错误的名字,因为你没有在你的蜘蛛中定义def start_requests() 并将它指向你的parse_all(),scrapy 默认只会理解parse()

    我觉得你应该把你的名字parse_all()改成parse()

    关于绝对/相对路径的问题。有一个技巧可以让您注意到网站的资产路径。如果您的链接包含该路径(可能采用http://domain/... 的形式),则它应该是绝对链接。使用相对路径,您可以手动将资产路径附加到它们并处理您的下载!

    检测链接是否可以作为文件下载的另一个技巧the file usually contain the extension, e.g. .pdf, .jpg ...

    【讨论】:

    • 感谢您的见解。我很感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2010-09-15
    • 2013-07-14
    • 2010-12-17
    • 1970-01-01
    • 2010-12-11
    • 2011-06-30
    相关资源
    最近更新 更多