第一个简单Python爬虫:抓取古诗文网中李白的诗歌

2018年10月11日  这是第一个博客,嘻嘻~~~~

最近老师给了个任务:爬取诗歌。于是乎,走上了爬虫道路,爬取了李白的诗歌。

感谢代码的原作者(唐诗三百首,源代码)。

遇到的问题与收获:

1.熟悉了正则表达式在HTML中的匹配规则,能够编写出相应的正则表达式

2.不能利用正则表达式返回同一页面多个相同标签的内容

附上代码

# -*- coding:utf-8 -*-
import re
import requests

def crawl(start_url):
    base_url = 'http://so.gushiwen.org'

    req_headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
    }

    for i in range(1, 126):

        restart_url = start_url + str(i) + '.aspx'
        print(restart_url)

        res = requests.get(restart_url, headers=req_headers)
        if res.status_code == requests.codes.ok:
            html = res.text

            # 获取所有诗的链接
            parttern_href = re.compile(r'<div class="cont">.*?<p><a .*? href="(.*?)" .*?>.*?</p>', flags=re.DOTALL)
            hrefs = re.findall(parttern_href, html)

            # 获取每一首诗的内容,并保存到本地
            with open('李白诗集.txt', mode='a', encoding='utf-8') as f:
                for href in hrefs:
                    href = base_url + href
                    res = requests.get(href, headers=req_headers)
                    if res.status_code == requests.codes.ok:
                        html = res.text
                        # 标题
                        parttern_title = re.compile(r'<div class="cont">.*?<h1 .*?>(.*?)</h1>', re.DOTALL)
                        title = re.search(parttern_title, html).group(1)
                        # 内容
                        parttern_content = re.compile(r'<div class="cont">.*?<div class="contson" id=".*?">(.*?)</div>',
                                                      re.DOTALL)
                        content = re.search(parttern_content, html).group(1)
                        content = re.sub(r'<br />', '\n', content)
                        content = re.sub(r'<p>', '', content)
                        content = re.sub(r'</p>', '', content)

                        print('正在获取 {title}'.format(title=title))
                        f.write('{title}{content}\n'.format(title=title, content=content))

if __name__ == '__main__':
    start_url = 'https://so.gushiwen.org/authors/authorvsw_b90660e3e492A'
    crawl(start_url)

运行结果

 

 

 

  • 7
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值