【问题标题】:Scrapy - saving links while following themScrapy - 在关注链接时保存链接
【发布时间】:2017-02-24 03:35:02
【问题描述】:

我对 Python 和 Scrapy 还很陌生,我认为答案应该很简单,但我自己很难弄清楚这一点。代码获取所有链接,跟随它们并记录文章的标题。我如何传递获取到我的项目的 url?我想将它使用的短链接与文章标题一起保存。谢谢

def parse(self, response):
    for url in response.xpath("//li[@id]/@data-shortlink").extract():
        yield scrapy.Request(url, callback=self.get_details)

def get_details(self, response):
        article = ArticleItem()
        article['title'] = response.xpath("//h1/text()").extract()
        yield article

【问题讨论】:

    标签: python scrapy scrapy-spider


    【解决方案1】:

    由于它包含在Response() object 中,您可以使用response.url 获取网址:

    def get_details(self, response):
            article = ArticleItem()
            article['title'] = response.xpath("//h1/text()").extract()
            article['url'] = response.url
            yield article
    

    【讨论】:

    • 效果很好。有没有办法让它复制我提供的短链接来解析,而不是它实际遵循的完整链接?
    • 我不确定是否诚实。我建议尝试和print()找出不同的Response subclass methods。或者,如果它是您提供给 parse() 的 arg,那么您似乎当然也应该能够将它传递给 get_details...
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 2019-05-02
    • 2011-10-26
    • 2015-02-01
    相关资源
    最近更新 更多