标签:__ txt name python pattern 爬取 Soup html 小说
from urllib import request from bs4 import BeautifulSoup import re,codecs def download(url,i=0):#下载网页 #获取HTML headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'} req = request.Request(url, headers=headers) html = request.urlopen(req).read() #保存HTML file_name = i with open ("{}.html".format(i),"wb") as f: f.write(html) with open('{}.html'.format(i), 'rb') as f: Soup = str(BeautifulSoup(f.read(), 'html.parser')) #把html转化为string return Soup def save(name,txt): # 得到标题和正文之后,保存为txt f = codecs.open("{}.txt".format(name),'w','utf-8') f.write(txt) def tackle(url,i): Soup = download(url,i) # 获取字符串,字符串内容为整个网页 pattern_title = '<div class="title">.*</div>' #匹配,其中.*代表匹配中间全部字符(除了换行) mp = re.search(pattern_title,Soup) #正则搜索 title = mp.group()[12:-6] # group方法返回搜索结果的字符串形式,并把字符串中<div class="title">和</div>去掉 start = Soup.find('<div class="content" id="content">') end = Soup.find('</p></div>') pattern_body = Soup[start+34:end] #标记正文位置 save(title+'.txt',pattern_body) if __name__ == "__main__": Soup = download('path') # 小说目录网址 place = [substr.start() for substr in re.finditer('http://www.ncwxw.cc/0/298/8',Soup)] # 字符串匹配,确定所有章节的网址位置 place = place[13:] #预处理 website = [] #存储每一章的网址 for chapter in place: website.append(Soup[chapter:chapter+36]) '''以上适用于每一章节网址无规律的情况,若有规律则可直接变址寻址''' for i in range(1,1979): tackle(website[i],i)
标签:__,txt,name,python,pattern,爬取,Soup,html,小说 来源: https://www.cnblogs.com/chengjunkai/p/15807131.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。