Scrapy 爬取链接
说明
在本章中,我们将研究如何提取我们感兴趣的页面的链接,关注它们并从该页面中提取数据。为此,我们需要在我们的之前的代码中进行以下更改,如下所示-
import scrapy
from tutorial.items import DmozItem
class MyprojectSpider(scrapy.Spider):
name = "project"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/",
]
def parse(self, response):
for href in response.css("ul.directory.dir-col > li > a::attr('href')"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback = self.parse_dir_contents)
def parse_dir_contents(self, response):
for sel in response.xpath('//ul/li'):
item = DmozItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('text()').extract()
yield item
上面的代码包含以下方法-
parse()-它将提取我们感兴趣的链接。
response.urljoin-parse() 方法将使用此方法构建一个新的 url 并提供一个新的请求,该请求将在稍后发送给回调。
parse_dir_contents()-这是一个回调,它实际上会抓取感兴趣的数据。
这里,Scrapy 使用回调机制来跟踪链接。使用这种机制,可以设计更大的爬虫,并可以跟随感兴趣的链接从不同的页面抓取所需的数据。常规方法将是回调方法,它将提取项目,寻找链接到下一页,然后提供相同回调的请求。
以下示例生成一个循环,它将跟随链接到下一页。
def parse_articles_follow_next_page(self, response):
for article in response.xpath("//article"):
item = ArticleItem()
... extract article data here
yield item
next_page = response.css("ul.navigation > li.next-page > a::attr('href')")
if next_page:
url = response.urljoin(next_page[0].extract())
yield scrapy.Request(url, self.parse_articles_follow_next_page)