实例学习——爬取《斗破苍穹》全文小说

 阅读前提:python基本语法

                   正则表达式

 开发环境:(Windows)eclipse+pydev

 http://爬取网址:www.doupoxs.com/doupocangqiong/

import requests
import re
import time

headers ={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'}
     #加入请求头,增加爬虫稳定性
f = open('D:\Pyproject\doupo\doupo.txt','a+')      #新建txt文档,以追加方式打开

def get_info(url):                 #每一页面的文本爬取函数
    res = requests.get(url,headers = headers)
    if res.status_code == 200:                     #判断请求码是否为200,若是,则成功,不是,则失败
        contents = re.findall('<p>(.*?)</p>',res.content.decode('UTF-8'),re.S)        #定义编码方式
        for content in contents:
            f.write(content+'\n')                  #正则获取数据写入txt文件
    else:
        pass
    
if __name__ =='__main__':      
    urls = ['http://www.doupoxs.com/doupocangqiong/{}.html'.format(str(i)) for i in range(2,1665)]  #总爬取页数
    for url in urls:
        get_info(url)                          
        time.sleep(1)
f.close()                                         #关闭文档

 结果展示:

 有关请求头获取方式等,见本人另一博文,不再赘述:爬取酷狗TOP500歌曲信息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值