Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 148.3MB ·虚拟内存 1437.8MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
在本章中,我们将研究如何提取感兴趣页面的链接,并关注它们并从该页面提取数据。为此,我们需要对以前的代码进行如下更改,如下所示:
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
以上代码包含以下方法:
在这里,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)
存储数据的最佳方法是使用Feed输出,这可确保使用多个序列化格式正确存储数据。JSON,JSON行,CSV,XML是序列化格式中支持的格式。数据可以通过以下命令存储:scrapy crawl dmoz -o data ...