【问题标题】:Python 3 TypeError: utf_8_encode() must be str not bytes using RequestsPython 3 TypeError: utf_8_encode() must be str not bytes using Requests
【发布时间】:2019-05-10 20:37:38
【问题描述】:

我正在尝试获取需要登录名和密码才能访问的 .txt 页面的内容。尝试通过页面并打印其内容时出现 TypeError:

TypeError: utf_8_encode() argument 1 must be str, not bytes

我访问这些数据的代码是:

import requests
with requests.Session() as c:
        url = 'https://www.naturalgasintel.com/user/login'
        data_url = 'https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/'
        username = 'manguy'
        password = 'hi123'
        c.get(url)
        login_data = dict(username=username, password=password)
        c.post(url, data=login_data, headers={'Referer':'https://www.naturalgasintel.com/'})
        page = c.get('https://naturalgasintel.com/ext/resources/Data-Feed/Daily-GPI/2018/10/20181009td.txt')
        print(page.content)

首先我访问父 url 登录然后使用数据 url 获取我想要的内容。

我需要将一些旧的 Python 2.0 模块命令 (Twill) 翻译成 Python 3.0 使用请求模块的命令。具体来说,我需要翻译这些行:

data = get_browser().result.get_page()
datafile = open(localfile, "w", encoding="utf-8")
datafile.write(data)
datafile.close()

我脚本中的page 基本上等同于原始脚本中的data,因此我可以将内容写入文件。

有没有简单的翻译方法?我需要以某种方式将字节转换为字符串吗?

【问题讨论】:

  • 我在 3.6.5 中没有遇到这样的错误
  • 我没有收到这个错误。我检查了request/urllib3,但utf8_encode 不存在。您能否提供有关您的回溯的更多详细信息。

标签: python python-3.x python-2.7 web-scraping python-requests


【解决方案1】:

错误来自文件写入,您可以使用

datafile = open(localfile, "wb")
datafile.write(page.content)
datafile.close()

或者

datafile = open(localfile, "w", encoding="utf-8")
datafile.write(page.text)
datafile.close()

【讨论】:

    猜你喜欢
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2015-04-17
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多