我试着从原始的嘻哈歌词档案中抓取歌词。在
我已经成功地写了一个蜘蛛,如果我把它放在艺术家页面上,像这样: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)
restrict_xpaths
不应指向@href
属性。它应该指向链接提取器将搜索链接的位置:请注意,您可以将其指定为字符串而不是元组。在
您还可以
^{pr2}$allow
所有包含all*.html
的链接:你还应该确保你的蜘蛛确实在访问“父目录”页面。开始爬行听起来很合理,因为这是目录的索引页:
第二部分这个答案对于抓取网页中的特定链接很有用。https://stackoverflow.com/a/40146522/4418897
相关问题 更多 >
编程相关推荐