1

如何使用scrapypython库制作以下爬虫,递归浏览整个网站:

class DmozSpider(BaseSpider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/"
    ]

def parse(self, response):

    hxs = HtmlXPathSelector(response)

    titles = hxs.select('//ul[@class="directory-url"]/li/a/text()').extract()

    for t in titles:
        print "Title: ", t

我在一个页面上试过这个:

start_urls = [
    "http://www.dmoz.org/Society/Philosophy/Academic_Departments/Africa/"
]

它运行良好,但仅从起始 url 返回结果,并且不遵循域内的链接。我想这必须手动完成,Scrapy但不知道如何。

4

1 回答 1

2

尝试使用 a CrawlSpider(请参阅文档),使用一个仅在您想要的域上过滤的Rule()a :LinkExtractor

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector

class DmozSpider(CrawlSpider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/"
    ]

    rules = (
        Rule(
            SgmlLinkExtractor(allow_domains=("dmoz.org",)),
            callback='parse_page', follow=True
        ),
    )

    def parse_page(self, response):
        hxs = HtmlXPathSelector(response)
        titles = hxs.select('//ul[@class="directory-url"]/li/a/text()').extract()
        for t in titles:
            print "Title: ", t

回调必须被称为其他东西parse(请参阅此警告

于 2013-08-14T08:51:01.733 回答