python - 抓取小说网页,不知如何处理编码问题
迷茫
迷茫 2017-04-18 09:06:20
[Python讨论组]

抓取小说网页,链接在代码中。数据处理为字典,写入txt文件中。不知道怎么处理编码问题,中文不能正确显示,折腾了整个晚上,还是不行,要死。
还有一个问题就是网页源代码中在

标签中经常插入----标签,搞到有些字抓取之后看不见,也求一并解答。
刚学python,望大神指点。首先感谢你宝贵的时间,谢谢。

# coding:utf-8
from lxml import etree
from multiprocessing.dummy import Pool as ThreadPool
import requests
import sys

reload(sys)

sys.setdefaultencoding('utf-8')

def towrite(contentdict):
    f.writelines(u'章:' + unicode(contentdict['title']) + '\n')
    f.writelines(unicode(contentdict['content']) + '\n\n')

def spider(url):
    head = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
    html = requests.get(url,headers = head)
    html.encoding = 'utf-8'
    print html.text
    seletor = etree.HTML(html.text)
    title = seletor.xpath('//p[@id="f_title1"]/h1/text()')
    content = seletor.xpath('//p[@id="f_content1"]/p/p/text()')
    fullcontent = ''
    for each in content:
        fullcontent += each
    # title.decode('gb2312').encode('utf-8')
    # fullcontent.encode('utf-8')
    item = {}
    item['title'] = title
    item['content'] = fullcontent
    towrite(item)

if __name__ == '__main__':
    pool = ThreadPool(4)
    f = open('guduliujiang.txt','a')
    page = []
    for i in range(1,29):
        newpage = 'http://www.sbkk8.cn/mingzhu/zhongguoxiandaiwenxuemingzhu/guduliujiang/' + str(145232-i) + '.html'
        page.append(newpage)

    results = pool.map(spider,page)
    pool.close()
    pool.join()
    f.close()
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
高洛峰

网页源码的编码是gb2312,不是utf-8

黄舟

requests搭配BeautifulSoup使用

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号