用python“爬”一篇小说-创新互联
需要你的python安装有requests模块,如果没有安装可执行如下命令安装

pip3 install requests
以最近比较火的小说“魔道祖师”为例。
下面是整个脚本
import requests,re
def get_content(url,timeout=10):
req = requests.get(url=url,timeout=timeout)
return req.text
def get_title(html,re_title):
ret = re_title.search(html)
if ret:
ret = ret.group()
tmp = ret.split('_')[0]
tmp = tmp.replace('','')
tmp = tmp.strip()
return tmp
def get_body(html,ret_body):
ret_body = re_body.search(html)
if ret_body:
ret = ret_body.group()
tmp = re_clear_header.sub(r'\2',ret)
tmp = tmp.replace(r' ',' ').replace(r'
','\n').replace(r'
','\n')
tmp = tmp.replace(r'2k小说阅读网','\n\n')
return tmp
if __name__ == '__main__':
mdzs = open('mdzs.txt','w')
re_title = re.compile(r'(.*?) ')
re_body = re.compile(r'(.*?)
',re.S)
re_clear_header = re.compile(r'(.*)(.*)',re.S)
first_page = 19613532
for i in range(116):
page = first_page + i
url = 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('{} is success'.format(url))
except Exception as e:
print('url :{} , error: {}'.format(url,e)) 该网站是小说网站,排版和网页的url比较有规律性,所以实现起来比较简单
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章标题:用python“爬”一篇小说-创新互联
分享链接:http://www.jxjierui.cn/article/ddgodo.html


咨询
建站咨询
