鱼C论坛

 找回密码
 立即注册
查看: 1858|回复: 11

[已解决]求助:网络爬虫编码问题!没辙了help!!

[复制链接]
发表于 2017-8-29 22:41:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 花蝴蝶¤ 于 2017-9-1 21:56 编辑

用python2.7爬取股票信息的时候遇到了如下编码问题: QQ图片20170829223247.png

转码前打印了一次发现是ascii格式,然后通过.decode('ascii').encode('utf-8')进行转码,但是转码后还是ascii格式的。并且输出文件里面的内容格式也是有点奇怪 。麻烦帮忙看一下哪里写错了,谢谢


完整代码如下:
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import traceback
import re
import random
import chardet


def getHTMLText(url):
    headers_list = [
        {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"},
        {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11"},
        {
            "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.17 Safari/537.11"}
    ]
    header = random.choice(headers_list)
    try:
        r = requests.get(url = url, headers = header)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
        #print(r.text)
    except:
        return ""
       
    
def getStockList(lst, stockURL):
    html = getHTMLText(stockURL)
    # print(chardet.detect(html))
    soup = BeautifulSoup(html, "html.parser")
    a = soup.find_all("a")
    for i in a:
        try:
            href = i.attrs['href']
            lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
        except:
            continue
    # print(chardet.detect(lst))


def getStockInfo(lst, stockURL, fpath):
    count = 0
    for stock in lst:
        url = stockURL + stock + ".html"
        html = getHTMLText(url)
        # print(chardet.detect(html))
        try:
            if html == "":
                continue
            infoDict = {}
            soup = BeautifulSoup(html, "html.parser")
            stockInfo = soup.find('div', attrs={'class':'stock-bets'})
            name = stockInfo.find_all(attrs = {'class':'bets-name'})[0]
            # print(name.text.split()[0])
            infoDict.update({'股票名称':name.text.split()[0]})
            # print(infoDict)
            keyList = stockInfo.find_all('dt')
            valueList = stockInfo.find_all('dd')
            for i in range(len(keyList)):
                key = keyList[i].text
                val = valueList[i].text
                # print(chardet.detect(key))
                # print(chardet.detect(val))
                infoDict[key] = val
            # print(infoDict)

            with open(fpath, 'a') as f:
                print(chardet.detect(str(infoDict)))
                content = str(infoDict).decode('ascii').encode('utf-8')
                print(chardet.detect(content))
                f.write( content + '\n')
                count += 1
                print("\r当前进度:{:.2f}%".format(count*100/len(lst)))
        except:

            count += 1
            print ("\r当前进度:{:.2f}%".format(count*100/len(lst)))
            continue
            

def main():
    stock_list_url = "http://quote.eastmoney.com/stocklist.html"
    stock_info_url = "https://gupiao.baidu.com/stock/"
    output_file = './gupiao.txt'
    slist = []
    getStockList(slist, stock_list_url)
    getStockInfo(slist, stock_info_url, output_file)
    
main()
最佳答案
2017-9-3 13:04:29
花蝴蝶¤ 发表于 2017-9-2 20:17
输出的文件内容是中文吗

没注意你的python是2.7。
直接用str将字典转换成字符串这个方法在2.7是有问题的。
你可以换个方法。
with .. as f:
    f.write('{')
    for i in dict:
        f.write(i+':'+dict[i])
    f.write('}')
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-8-29 23:28:12 | 显示全部楼层
刚刚才发现贴中的代码多了一条线。。可能是论坛限制了,直接复制代码应该可以粘贴的,粘贴不了哪位大神愿意帮忙看一下的话我可以再单独发!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-8-30 20:43:33 | 显示全部楼层
decode('gbk').encode('utf-8')
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-1 21:57:38 | 显示全部楼层
domenet 发表于 2017-8-30 20:43
decode('gbk').encode('utf-8')

不好意思回复慢了。decode('gbk').encode('utf-8')改了还是不行。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-2 09:56:40 | 显示全部楼层
你这应该是个mac吧。
改下python默认编码试下。
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-2 19:27:21 | 显示全部楼层
谢谢你的帮助,我用的系统是ubuntu.16.4版本的,加你给的代码后运行程序没有报错但是也没有结果输出。请问代码在你电脑上能正常输出吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-2 19:28:07 | 显示全部楼层
wei_Y 发表于 2017-9-2 09:56
你这应该是个mac吧。
改下python默认编码试下。


谢谢你的帮助,我用的系统是ubuntu.16.4版本的,加你给的代码后运行程序没有报错但是也没有结果输出。请问代码在你电脑上能正常输出吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-2 19:43:11 | 显示全部楼层
花蝴蝶¤ 发表于 2017-9-2 19:28
谢谢你的帮助,我用的系统是ubuntu.16.4版本的,加你给的代码后运行程序没有报错但是也没有结果输出。 ...

我这里是win7, py3.4. 把用了chardet的去掉正常运行。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-2 20:17:08 | 显示全部楼层
wei_Y 发表于 2017-9-2 19:43
我这里是win7, py3.4. 把用了chardet的去掉正常运行。

输出的文件内容是中文吗
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-9-3 13:04:29 | 显示全部楼层    本楼为最佳答案   
花蝴蝶¤ 发表于 2017-9-2 20:17
输出的文件内容是中文吗

没注意你的python是2.7。
直接用str将字典转换成字符串这个方法在2.7是有问题的。
你可以换个方法。
with .. as f:
    f.write('{')
    for i in dict:
        f.write(i+':'+dict[i])
    f.write('}')

评分

参与人数 1荣誉 +5 鱼币 +5 贡献 +3 收起 理由
花蝴蝶¤ + 5 + 5 + 3 感谢楼主无私奉献!

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-3 15:26:01 | 显示全部楼层
wei_Y 发表于 2017-9-3 13:04
没注意你的python是2.7。
直接用str将字典转换成字符串这个方法在2.7是有问题的。
你可以换个方法。


很奇怪,用了这种方式输出文件里面没有内容只有很多的左括号‘{’。但是在pycharm里面打印write之前的数据是能显示中文的。
QQ截图20170903151751.png
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-9-3 15:32:49 | 显示全部楼层
wei_Y 发表于 2017-9-3 13:04
没注意你的python是2.7。
直接用str将字典转换成字符串这个方法在2.7是有问题的。
你可以换个方法。

可以了!把你教的两种方法都一起用上输出就是中文了,多谢啊!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 09:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表