Scrapy:尝试将索引中的每个链接作为完整的html fi下载失败

2024-09-29 08:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问索引中的每个链接,并用html保存相应的页面。我尝试将LinkExtractor的使用与整页下载结合起来——本质上是将这两种方法结合起来:Scrapy-Recursively Scrape Webpages and save content as html fileDownload a full page with scrapy

但是,我生成了一个指向define parse\u item函数的错误(第17行)。我想这和18号线有关。你知道吗

当我在一个url上使用parse函数时,它可以正常工作,但当我尝试将它合并到LinkExtractor中时就不行了。你知道吗

我的蜘蛛.py代码如下:

import scrapy
import urlparse
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class EasySpider(CrawlSpider):
    name = 'easy'
    allowed_domains = ['web']
    start_urls = ['http://www.example.com/index.html']

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//*[@class="foobar"]//a/@href'), 
             callback='parse_item')
    )

def parse_item(self, response):
    filename = urlparse.urljoin(response.url, url)
    with open(filename, 'wb') as f:
        f.write(response.body)

    return

这是因为语法问题还是我需要创建/修改项目.py?我很确定我对urlparse组件做了一些错误,但是我尝试过的所有变体都没有让我通过这个错误。你知道吗

任何帮助都将不胜感激。 谨致问候


Tags: 函数frompyimporturlparseresponsehtml
1条回答
网友
1楼 · 发布于 2024-09-29 08:28:56

您的问题是parse_item不在类内部,而是在类外部。所以它不会成为你蜘蛛的一部分

import scrapy
import urlparse
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class EasySpider(CrawlSpider):
    name = 'easy'
    allowed_domains = ['web']
    start_urls = ['http://www.example.com/index.html']

    rules = (
        Rule(LinkExtractor(restrict_xpaths='//*[@class="foobar"]//a'), 
             callback='parse_item'), 
    )

    def parse_item(self, response):
       filename = "index.html"
       with open(filename, 'wb') as f:
           f.write(response.body)

       return

相关问题 更多 >