让 scrapy 跟踪页面上的特定链接

Getting scrapy to follow specific links on a page

我正在尝试从 The Original Hip Hop Lyrics Archive 中抓取歌词。

如果我在艺术家页面上发布它,我已经设法编写了一个抓取艺术家歌词的蜘蛛程序,例如:http://www.ohhla.com/anonymous/aesoprck/

但是当我在这个页面上发布它并链接到不同的艺术家页面时 http://www.ohhla.com/all.html 我什么也没得到。

这是我尝试用来跟踪艺术家页面链接的规则:

Rule(LinkExtractor(restrict_xpaths=('//pre/a/@href',)), follow= True)

这是我尝试使用的规则,用于跟踪指向不同页面的链接以及指向艺术家页面的链接:

Rule(LinkExtractor(restrict_xpaths=('//h3/a/@href',)), follow= True)

我修改了 Scrapy 中的教程以使其正常工作,因为出于某种原因当我开始一个新项目时它不起作用。

这是我的蜘蛛的完整工作示例:

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


class ohhlaSpider(CrawlSpider):
    name = "ohhla"
    download_delay = 0.5
    allowed_domains = ["ohhla.com"]
    start_urls = ["http://www.ohhla.com/anonymous/aesoprck/"]
    rules = (Rule (LinkExtractor(restrict_xpaths=('//h3/a/@href',)), follow= True), # trying to follow links to pages with more links to artist pages
             Rule (LinkExtractor(restrict_xpaths=('//pre/a/@href',)), follow= True), # trying to follow links to artist pages
             Rule (LinkExtractor(deny_extensions=("txt"),restrict_xpaths=('//ul/li',)), follow= True), # succeeding in following links to album pages
             Rule (LinkExtractor(restrict_xpaths=('//ul/li',)), callback="extract_text", follow= False),) # succeeding in extracting lyrics from the songs on album pages

    def extract_text(self, response):
        """ extract text from webpage"""
        string = response.xpath('//pre/text()').extract()[0]
        with open("lyrics.txt", 'wb') as f:
            f.write(string)

restrict_xpaths 不应指向 @href 属性。它应该指向 link 提取器将搜索 links:

的位置
Rule(LinkExtractor(restrict_xpaths='//h3'), follow=True)

请注意,您可以将其指定为字符串而不是元组。


您还可以 allow 所有包含 all*.html 的 link:

Rule(LinkExtractor(allow=r'all.*?\.html'), follow=True)

您还应该确保您的蜘蛛程序确实在访问该 "Parent Directory" 页面。开始使用它进行爬网听起来合乎逻辑,因为这是目录的索引页:

start_urls = ["http://www.ohhla.com/all.html"]

此答案的第二部分可用于抓取网页中的特定链接。