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')
第一个python爬虫,爬虫的基本步骤
最新推荐文章于 2024-08-07 08:19:34 发布