引自免费微信小程序:皆我百晓生
为了解决你的问题,我们可以按照你提供的步骤来创建一个Scrapy项目来爬取古诗文网的唐诗三百首。下面是一份详细的指南,包括代码示例。
一、创建项目
首先,在命令行中运行以下命令创建一个新的Scrapy项目:
scrapy startproject gushiwen
这将创建一个名为gushiwen的新目录,其中包含你的Scrapy项目的基本结构。
二、创建爬虫文件
进入项目目录后,创建一个爬虫:
cd gushiwen
scrapy genspider tangshi tangshi "https://www.gushiwen.cn/gushi/tangshi.aspx"
这将生成一个名为tangshi.py的爬虫文件在gushiwen/spiders目录下。
三、设置 items.py
在gushiwen/items.py中定义要抓取的字段:
import scrapy
class GushiwenItem(scrapy.Item):
title = scrapy.Field()
author = scrapy.Field()
dynasty = scrapy.Field()
content = scrapy.Field()
tags = scrapy.Field()
url = scrapy.Field()
四、settings.py
确保ROBOTSTXT_OBEY被设置为False,并启用你需要的管道(如果有的话):
# gushiwen/settings.py
ROBOTSTXT_OBEY = False
# Enable or disable item pipelines
ITEM_PIPELINES = {
'gushiwen.pipelines.GushiwenPipeline': 300,
}
五、编写爬虫程序
编辑gushiwen/spiders/tangshi.py:
import scrapy
from gushiwen.items import GushiwenItem
class TangshiSpider(scrapy.Spider):
name = 'tangshi'
allowed_domains = ['www.gushiwen.cn']
start_urls = ['https://www.gushiwen.cn/gushi/tangshi.aspx']
def parse(self, response):
# 提取每个古诗的链接
poem_links = response.css('.sons a::attr(href)').getall()
for link in poem_links:
yield response.follow(link, self.parse_poem)
def parse_poem(self, response):
item = GushiwenItem()
item['title'] = response.css('.cont h1::text').get()
item['author'] = response.css('.cont p.source a::text').getall()[0]
item['dynasty'] = response.css('.cont p.source a::text').getall()[1]
item['content'] = response.css('.cont .contson::text').getall()
item['tags'] = response.css('.tag a::text').getall()
item['url'] = response.url
yield item
六、编写管道
如果你需要存储数据,可以在gushiwen/pipelines.py中添加一个管道:
# gushiwen/pipelines.py
class GushiwenPipeline:
def process_item(self, item, spider):
# 在这里处理或存储item
return item
运行爬虫
最后,回到项目的根目录,并运行爬虫:
scrapy crawl tangshi
以上就是完整的步骤和代码示例,用于爬取古诗文网的唐诗三百首。确保网络连接良好,并且网站的结构没有改变,否则可能需要调整CSS选择器。