• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python制作爬虫采集小说

python 搞代码 4年前 (2022-01-09) 53次浏览 已收录 0个评论

开发工具:python3.4
操作系统:win8
主要功能:去指定小说网页爬小说目录,按章节保存到本地,并将爬过的网页保存到本地配置文件。
被爬网站:http://www.cishuge.com/
小说名称:灵棺夜行
代码出处:本人亲自码的

import urllib.requestimport http.cookiejarimport socketimport timeimport retimeout = 20socket.setdefaulttimeout(timeout)sleep_download_time = 10time.sleep(sleep_download_time) def makeMyOpener(head = { 'Connection': 'Keep-Alive', 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'}): cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) header = [] for key, value in head.items():  elem = (key, value)  header.append(elem) opener.addheaders = header return opener def saveFile(save_path,txts): f_obj = open(save_path,'w+') for item in txts:  f_obj.write(item+'\n') f_obj.close() #get_code_listcode_list='http://www.cishuge.com/read/0/771/'oper = makeMyOpener()uop = oper.open(code_list,timeout=1000)data = uop.read().decode('gbk','ignore')pattern = re.compile('<li>(.*?)</li>',re.S)items = re.findall(pattern,data)print ('获取列表完成')url_path='url_file.txt'url_r=open(url_path,'r')url_arr=url_r.readlines(100000)url_<strong>本文来源gao@daima#com搞(%代@#码@网2</strong>r.close()print (len(url_arr))url_file=open(url_path,'a')print ('获取已下载网址')for tmp in items: save_path = tmp[1].replace(' ','')+'.txt' url = code_list+tmp[0] if url+'\n' in url_arr:  continue print('写日志:'+url+'\n') url_file.write(url+'\n') opene = makeMyOpener() op1 = opene.open(url,timeout=1000) data = op1.read().decode('gbk','ignore') opene.close() pattern = re.compile('    (.*?)<br />',re.S) txts = re.findall(pattern,data) saveFile(save_path,txts) url_file.close()

虽然代码还是有点瑕疵,还是分享给大家,一起改进


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python制作爬虫采集小说
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址