用python“爬”一篇小说,,需要你的python
用python“爬”一篇小说,,需要你的python
需要你的python安装有requests模块,如果没有安装可执行如下命令安装pip3installrequests
以最近比较火的小说“魔道祖师”为例。
下面是整个脚本
importrequests,redefget_content(url,timeout=10):req=requests.get(url=url,timeout=timeout)returnreq.textdefget_title(html,re_title):ret=re_title.search(html)ifret:ret=ret.group()tmp=ret.split('_')[0]tmp=tmp.replace('<title>','')tmp=tmp.strip()returntmpdefget_body(html,ret_body):ret_body=re_body.search(html)ifret_body:ret=ret_body.group()tmp=re_clear_header.sub(r'\2',ret)tmp=tmp.replace(r' ','').replace(r'<br/><br/>','\n').replace(r'<br/>','\n')tmp=tmp.replace(r'2k小说阅读网</p>','\n\n')returntmpif__name__=='__main__':mdzs=open('mdzs.txt','w')re_title=re.compile(r'<title>(.*?)</title>')re_body=re.compile(r'<pclass="Text">(.*?)</p>',re.S)re_clear_header=re.compile(r'(.*</script>)(.*)',re.S)first_page=19613532foriinrange(116):page=first_page+iurl=r'https://www.2kxs.com/xiaoshuo/96/96717/{}.html'.format(page)try:html=get_content(url)title=get_title(html,re_title)mdzs.write(title+'\n\n')body=get_body(html,re_body)mdzs.write(body)print('{}issuccess'.format(url))exceptExceptionase:print('url:{},error:{}'.format(url,e))
该网站是小说网站,排版和网页的url比较有规律性,所以实现起来比较简单
用python“爬”一篇小说
相关内容
- python学习之基础内容,,python基础内容
- python1、2实践,,一、实践需求 输入
- Python将依赖包导出到requirements.txt文件,,代码# 查询环境
- Python股票量化第一步环境搭建,,很久之前就希望可以量
- 利用python 获取网址中的href(基于python 3.6),,import url
- python 爬虫,,scrapy处理选中
- Python scipy.sparse矩阵使用方法,,本文以csr_mat
- python nose测试框架全面介绍五--attr介绍,,之前写了一系
- python 课后习题 猜数游戏,,4.1 猜数游戏。在
- 【Python】从汇率转换算法谈起,,CurStr = i
评论关闭