鱼C论坛

 找回密码
 立即注册
查看: 1824|回复: 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格式的。并且输出文件里面的内容格式也是有点奇怪 。麻烦帮忙看一下哪里写错了,谢谢


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

  2. import requests
  3. from bs4 import BeautifulSoup
  4. import traceback
  5. import re
  6. import random
  7. import chardet


  8. def getHTMLText(url):
  9.     headers_list = [
  10.         {
  11.             "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"},
  12.         {
  13.             "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11"},
  14.         {
  15.             "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.17 Safari/537.11"}
  16.     ]
  17.     header = random.choice(headers_list)
  18.     try:
  19.         r = requests.get(url = url, headers = header)
  20.         r.raise_for_status()
  21.         r.encoding = r.apparent_encoding
  22.         return r.text
  23.         #print(r.text)
  24.     except:
  25.         return ""
  26.       
  27.    
  28. def getStockList(lst, stockURL):
  29.     html = getHTMLText(stockURL)
  30.     # print(chardet.detect(html))
  31.     soup = BeautifulSoup(html, "html.parser")
  32.     a = soup.find_all("a")
  33.     for i in a:
  34.         try:
  35.             href = i.attrs['href']
  36.             lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
  37.         except:
  38.             continue
  39.     # print(chardet.detect(lst))


  40. def getStockInfo(lst, stockURL, fpath):
  41.     count = 0
  42.     for stock in lst:
  43.         url = stockURL + stock + ".html"
  44.         html = getHTMLText(url)
  45.         # print(chardet.detect(html))
  46.         try:
  47.             if html == "":
  48.                 continue
  49.             infoDict = {}
  50.             soup = BeautifulSoup(html, "html.parser")
  51.             stockInfo = soup.find('div', attrs={'class':'stock-bets'})
  52.             name = stockInfo.find_all(attrs = {'class':'bets-name'})[0]
  53.             # print(name.text.split()[0])
  54.             infoDict.update({'股票名称':name.text.split()[0]})
  55.             # print(infoDict)
  56.             keyList = stockInfo.find_all('dt')
  57.             valueList = stockInfo.find_all('dd')
  58.             for i in range(len(keyList)):
  59.                 key = keyList[i].text
  60.                 val = valueList[i].text
  61.                 # print(chardet.detect(key))
  62.                 # print(chardet.detect(val))
  63.                 infoDict[key] = val
  64.             # print(infoDict)

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

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

  77. def main():
  78.     stock_list_url = "http://quote.eastmoney.com/stocklist.html"
  79.     stock_info_url = "https://gupiao.baidu.com/stock/"
  80.     output_file = './gupiao.txt'
  81.     slist = []
  82.     getStockList(slist, stock_list_url)
  83.     getStockInfo(slist, stock_info_url, output_file)
  84.    
  85. main()
复制代码

最佳答案
2017-9-3 13:04:29
花蝴蝶¤ 发表于 2017-9-2 20:17
输出的文件内容是中文吗

没注意你的python是2.7。
直接用str将字典转换成字符串这个方法在2.7是有问题的。
你可以换个方法。
  1. with .. as f:
  2.     f.write('{')
  3.     for i in dict:
  4.         f.write(i+':'+dict[i])
  5.     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默认编码试下。
  1. import sys
  2. reload(sys)
  3. 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是有问题的。
你可以换个方法。
  1. with .. as f:
  2.     f.write('{')
  3.     for i in dict:
  4.         f.write(i+':'+dict[i])
  5.     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-4-27 12:50

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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