安装scrapy库方法
pip install scrapy
检查Scrapy的版本:
scrapy version
这个爬虫使用了Scrapy自带的Spider类,并定义了一个名为QuotesSpider的子类。在start_urls中定义了初始爬取的URL,并在parse()方法中定义了如何处理响应的逻辑。
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = [
'http://xxx.com/xxx/',
]
def parse(self, response):
for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('span small::text').get(),
'tags': quote.css('div.tags a.tag::text').getall(),
}
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
yield response.follow(next_page, self.parse)
AI生成:2023年6月16日