使用 Scrapy 的 LinkExtractor

Kur*_*eek 3 python scrapy

我正在尝试使用 Scrapy 从页面中提取所有链接,但正在努力使用 LinkExtractor。我尝试了以下方法:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from Funda.items import FundaItem

class FundaSpider(scrapy.Spider):
    name = "Funda"
    allowed_domains = ["funda.nl"]
    start_urls = [
        "http://www.funda.nl/koop/amsterdam/"
    ]
    rules = (
    Rule(LinkExtractor(), callback='parse_item')
    )

    def parse_item(self, response):
        filename = response.url.split("/")[-2] + '.html'
        with open(filename, 'wb') as f:
            f.write(response.body)
Run Code Online (Sandbox Code Playgroud)

我的理解是,包括LinkExtractor()作为 aRule应该使response仅包含链接。但是,如果我查看amsterdam.html这样生成的文件,它似乎仍然包含整个网页,而不仅仅是链接。

我怎样才能让response只包含链接?

Gra*_*rus 6

为什么你会认为它只包含链接?

我认为你误解CrawlSpiderrule论点和论点。在rule您内部实际指定爬网逻辑而不是解析逻辑。解析正在指定的函数中处理callback

因此,如果您想只保存响应中的链接,则必须先从响应中提取它们。你甚至可以使用相同的LinkExtractor

class Spider(scrapy.Spider):
    name = 'spider1'
    le1 = LinkExtractor()
    rules = (
        Rule(le1, callback='parse_item')
    )

    def parse_item(self, response):
        # this will give you Link objects
        links = self.le1.extract_links(response)
        # this will give you html nodes of <a> 
        links = response.xpath("//a").extract()
Run Code Online (Sandbox Code Playgroud)