梦小兮 2024-06-13 18:50 采纳率: 33.3%
浏览 52

python爬虫 爬取唐诗三百首的二级页面全部代码

爬取古诗词网https://www.gushiwen.cn/中各项分类内容,例如唐诗三百首、古诗词三百首等
以唐诗三百首页面
需求:
1、一次页面提取所有古诗的链接
2、二次页面提
步骤
一、创建:
1、创建项目: scrapy startproject gushi
2、创建爬虫文件: cd .\Che168
scrapy genspider gushiSpiders
so.gushiwen.cn/gushi/tangshi.aspx
二、设置 items . py ,添加爬取的字段
三、 settings . py ,修改配置
1、禁用 reboots 协议: ROBOTSTXT _ OBEY = False
2、启用管道设置: ITEM _ PIPELINES
四、Che168Spiders. py ,编写爬虫程序,解析
提取所需要的数据
五、 pipelines . py ,编写管道数据函数
02-02古诗文网﹣二级页面
gushi

img

  • 写回答

4条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-06-13 18:50
    关注

    引自免费微信小程序:皆我百晓生

    为了解决你的问题,我们可以按照你提供的步骤来创建一个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选择器。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 6月13日