在一个页面上跟踪特定的链接

2024-09-30 08:36:38 发布

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

我试着从原始的嘻哈歌词档案中抓取歌词。在

我已经成功地写了一个蜘蛛,如果我把它放在艺术家页面上,像这样:http://www.ohhla.com/anonymous/aesoprck/,它可以抓取一个艺术家的歌词。在

但是,当我在这个页面上发布它时,我却什么也没有得到。在

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

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

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

^{pr2}$

我修改了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)

Tags: totextfromtrueextract页面linkspages
2条回答

restrict_xpaths不应指向@href属性。它应该指向链接提取器将搜索链接的位置:

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

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


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

^{pr2}$

你还应该确保你的蜘蛛确实在访问“父目录”页面。开始爬行听起来很合理,因为这是目录的索引页:

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

第二部分这个答案对于抓取网页中的特定链接很有用。https://stackoverflow.com/a/40146522/4418897

相关问题 更多 >

    热门问题