让蜘蛛爬满整个房间

2024-05-17 07:16:38 发布

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

我正在使用scrapy来抓取我拥有的旧站点,我正在使用下面的代码作为我的蜘蛛。我不介意为每个网页输出文件,或者一个包含所有内容的数据库。但我确实需要让蜘蛛爬行整个事情,而不是我必须把我现在必须做的每一个网址

import scrapy

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["www.example.com"]
    start_urls = [
        "http://www.example.com/contactus"
    ]

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

Tags: 文件代码com数据库网页内容站点example
1条回答
网友
1楼 · 发布于 2024-05-17 07:16:38

要对整个站点进行爬网,应该使用CrawlSpider而不是scrapy.Spider

Here's an example

出于您的目的,请尝试使用以下方法:

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

class MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (
        Rule(LinkExtractor(), callback='parse_item', follow=True),
    )

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

另外,看看这个article

相关问题 更多 >