码迷,mamicode.com
首页 > 编程语言 > 详细

python正则表达式——爬取网络小说实例

时间:2020-02-08 00:53:30      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:info   img   target   name   表达   sts   can   mamicode   head   

Python 正则表达式 菜鸟教程已经讲的很详细了,这里给出实例:

爬取斗破苍穹http://www.doupoxs.com/doupocangqiong/1.html

技术图片

运行截图:

技术图片

 

源代码:

import requests
import re
import time

headers = {
    ‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36‘
}

f = open(‘D:/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  #不为200就pass

if __name__ == ‘__main__‘:
    urls = [‘http://www.doupoxs.com/doupocangqiong/{}.html‘.format(str(i)) for i in range(2,100)]
    for url in urls:
        get_info(url)
        time.sleep(1)
    f.close()

 

python正则表达式——爬取网络小说实例

标签:info   img   target   name   表达   sts   can   mamicode   head   

原文地址:https://www.cnblogs.com/sengzhao666/p/12274980.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!