python requests 爬小说

遇到了编码错误真的很蛋疼,卡了2个小时才解决!
参考文献1参考文献2参考文献3

网站示例一:
# -*- coding: utf-8 -*-

import requests, re
from bs4 import BeautifulSoup

content='http://www.8shuw.com/BookReader/24-24559.html'  #目录页
resp = requests.get(content)
resp.encoding = 'gbk'
soup=BeautifulSoup(resp.text,'lxml')
tbody = soup.find('table',{'border':'0','class':'acss'}).find('tbody')
trs = tbody.find_all('a',{'itemprop':'url','href': True})
trs = [tr for tr in trs if re.match(u'^第.*$',tr.text) != None]  #排除一些没用的章节
#print('Count:',len(trs))
#print(trs[-1].text,'href =',trs[-1].get('href'))

with open ('novel.txt', 'w') as f:
    for chapter in reversed(trs):
        f.write(chapter.text+'\n')
        resp = requests.get(chapter.get('href'))
        resp.encoding = 'gbk'
        soup=BeautifulSoup(resp.text,'lxml')
        texts = soup.find('div',{'id':'readtext','class':'fontm'}).find_all('p')
        print(trs.index(chapter),chapter.text)
        for line in texts:
            #解决错误关键点,encode后再decode,加上ignore参数忽略一些解码错误
            f.write(re.sub(r'CNZZ_SLOT_RENDER\(\"\d{3,8}\"\)\;','',line.text.encode('gb18030').decode('gbk','ignore'))+'\n') 
    f.close()
网站示例二:
import requests, re
from bs4 import BeautifulSoup

content='http://www.piaotian.com/html/5/5896/'

resp = requests.get(content)
resp.encoding = 'gbk'
soup=BeautifulSoup(resp.text,'lxml')
tbody = soup.find('div',{'class':'centent'})
trs = tbody.find_all('a',{'href': True})
trs = [tr for tr in trs if re.match(u'^第.*$',tr.text) != None]
print('Count:',len(trs))
print(trs[1980].text,'href =',trs[1980].get('href'))

#print(re.sub(r'CNZZ_SLOT_RENDER\(\"\d{3,8}\"\)\;','',texts[1].text))
with open ('novel.txt', 'w') as f:
    for chapter in trs[1980:]: # 倒序目录 reversed(trs):
        print(trs.index(chapter),chapter.text)
        f.write(chapter.text+'\n')  # 章节标题
        resp = requests.get(content + chapter.get('href'))
        #resp.encoding = 'gb18030'
        soup=BeautifulSoup(resp.text,'html.parser')  #这里解析器不同于前例
        texts = soup.find_all('br')
        #print(soup.get_text())
        for line in texts:
            if len(line.text)>0:
                f.write(line.text.encode('utf-8').decode('gbk','ignore')+'\n')
    f.close()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,523评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,252评论 4 61
  • HDR下的风景大片 大家在拍照的时候有木有注意到相机设置里一个叫“HDR”的选项,大家知道它真正的作用是什么吗?还...
    SMU_黑科技阅读 1,316评论 3 1
  • 2016/01/31 『纵』 渴望随心所欲的自己像是终于被松了绑似的,毫无顾及的挥斥着自己的利剑肆意纵横。却忘了提...
    蒙奇奇_阿蒙蛮好的阅读 292评论 0 1