×

python TypeError 报错 乱码 gbk

抓取网页源代码写入文本文件遇到的2个报错处理

鹭岛小千 鹭岛小千 发表于2021-09-02 22:31:34 浏览839 评论0

抢沙发发表评论

【问题描述】编写了以下代码抓取网页源代码写入文本文件:

import requests

url = 'http://fund.eastmoney.com/company/default.html'
res = requests.request('GET',url)
if (res.status_code == 200):
     with open('d:/py/content.txt','w') as f:
         f.write(res.content)
    with open('d:/py/text.txt','w') as f:
        f.write(res.text)

运行后抛出以下2个错误:

TypeError: write() argument must be str, not bytes

UnicodeEncodeError: 'gbk' codec can't encode character '\xef' in position 0: illegal multibyte sequence

36-1.png

【小千解答】修改代码如下:

import requests

url = 'http://fund.eastmoney.com/company/default.html'
res = requests.request('GET',url)
if (res.status_code == 200):
    with open('d:/py/content.txt','wb') as f: # w改成wb
        f.write(res.content)
    with open('d:/py/text.txt','w',encoding=res.encoding) as f: # 设置encoding参数
        f.write(res.text)

注解:res.content返回bytes类型,res.text返回str类型,但和文本文件的编码不匹配。


打赏码.png


【参考资料】

  1. Requests Developer Interface

  2. TypeError: write() argument must be str, not bytes报错原因及Python3写入二进制文件方法

  3. 'gbk' codec can't encode character解决方法


群贤毕至

访客