第一个python爬虫,爬虫的基本步骤

import requests
import re#正则表达式模块
# 下载一个网页
url='http://www.jingcaiyuedu.com/book/15205.html'#统一资源定位符是URL
#模拟浏览器发送http请求
#添加一个headers更好地模拟浏览器的请求
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/51.0.2704.63 Safari/537.36'}

response=requests.get(url,headers=headers)#通过requests请求资源,response是响应的结果
response.encoding='utf-8'#设置编码方式
html=response.text#拿到主页信息
# print(html)
#获取章节内容
dl=re.findall(r' <dl class="panel-body panel-chapterlist">.*?</dl>',html,re.S)[0]
chapter_info_list=re.findall(r'href="(.*?)">(.*?)<',dl)#正则表达式以列表的形式提取每一章信息,其中加()会返回括号里面的东西
# print(chapter_info_list)#输出章节信息
#循环每一个章节,分别下载,下载前先获取小说名称
title=re.findall(r' <meta property="og:title" content="(.*?)"/>',html)[0]#小说名称
#新建一个文件保存小说内容
# with open('%s.txt' % title) as f:
fb=open('%s.txt' % title,'w',encoding='utf-8')#以写的方式打开文件
# print(title)
for chapter in chapter_info_list:
    # chapter_title=chapter[1]
    # chapter_url=chapter[0]
    chapter_url, chapter_title=chapter
    chapter_url="http://www.jingcaiyuedu.com%s" % chapter_url#以这种方式拼接字符串而不是以+,可以防止生成过的的字符串对象
    print(chapter_url)
    #下载章节内容
    chapter_response=requests.get(chapter_url,headers)
    chapter_response.encoding='utf-8'
    chapter_html=chapter_response.text#拿到这一张的html
    #正则表达式提取章节内容
    # chapter_content=re.findall(r'<div class="panel-body" id="htmlContent">(.*?)<a class="btn btn-info" '
    #                            r'href="/book/15205.html">',chapter_html)
    print(chapter_html)
    chapter_content = re.findall(r'"htmlContent">(.*?)<p class="text-center pt10">', chapter_html, re.S)[0]
    print(chapter_content[0])
    #数据持久化
    fb.write(chapter_title)
    fb.write(chapter_content)
    fb.write('\n')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值