【问题标题】:Python - TypeError: write() argument must be str, not bytesPython - TypeError:write() 参数必须是 str,而不是字节
【发布时间】:2020-03-29 02:05:14
【问题描述】:

我收到一条来自 python 的错误消息。 这是从牛津在线词典中提取音标的代码。

Traceback(最近一次调用最后一次):文件 “C:\Download\Oxford_PhoneticSymbol\Oxford_PhoneticSymbol.py”,第 24 行, 在 fw.write((result + "\n").encode("utf-8")) TypeError: write() argument must be str, not bytes

原文来自; https://my.oschina.net/sfshine/blog/3076588

# -*- coding: UTF-8 -*-
import requests
import time
from bs4 import BeautifulSoup
f = open('./words.txt')
fw = open('./result.txt','a')

line = f.readline()
index = 0
while line:
    index = index+1
    url = "https://www.oxfordlearnersdictionaries.com/definition/english/" + line.strip()
    print(str(index) + ":" + url)
    wbdata = requests.get(url,headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36'}).text
    soup = BeautifulSoup(wbdata,'html.parser')
    news_titles = soup.select("span.pron-g > span.phon")
    # print(news_titles)
    result = ''
    for n in news_titles:   
        title = n.get_text()    
        if 'NAmE' in title:
            result += '['+title.replace('NAmE','').replace('//','') + ']'
    print(result)  
    fw.write((result + "\n").encode("utf-8"))
    line = f.readline()
    time.sleep(0.1)

fw.close()
f.close()

根据需要,我将两个 txt 文件放在同一个目录中。 然后我在words.txt中填了几个字,把result.txt设为空白,却报错了。

(words.txt, saved as UTF-8)
source
technic
resource
power
box
created
computer
charged
learned

知道如何解决这个问题吗?

【问题讨论】:

  • 你试过把你的 open, fw = open('./result.txt','a') 从 'a' 改成 'ab'
  • 您在写(result + "\n").encode("utf-8") 时认为自己做了什么?错误消息非常清楚发生了什么,您熟悉字节与字符串吗?编辑:从头开始,我看到你正在复制一个教程,这是一个关于人们如何混淆字节和字符串的非常可悲的例子。
  • @ChristianSloper 我刚刚尝试将 a 更改为 ab,它有效,但错过了一些。谢谢你的建议。 *source (none) / technic (none, it doesn't exist on oxford) / resource [ˈriːsɔːrs][rɪˈsɔːrs] / power [ˈpaʊər] / box [bɑːks] / created (none) / computer [kəmˈpjuːtər] /charged [tʃɑːrdʒd ] / 学会了 [ˈlɜːrnɪd][lɜːrnd]
  • 您在这个问题中有一个具有误导性的链接。它当前显示一个 URL,但实际上链接到另一个 URL。请edit您的问题,以便显示的 URL 与链接实际链接到的 URL 相同。这可能只是一个格式错误,但不清楚您实际上想要链接到哪个 URL,所以我没有修复它。
  • 糟糕,感谢您的评论。链接已修复。

标签: python web-scraping


【解决方案1】:

将下载的页面保存到文件时出现此错误的解决方法:

TypeError: write() 参数必须是 str,而不是字节

是:

fw = open('./result.txt','wb')

二进制的“b”会有所不同。

【讨论】:

  • 谢谢你。天哪,我正在努力学习这种外星语言。那么我应该改变哪一个或者把 outFile = open('output.xml', 'wb')
  • 我已将 fw = open('./result.txt','a') 更改为 outFile = open('output.xml', 'wb') 并且我再次遇到错误。 fw.write((result + "\n").encode("utf-8")) NameError: name 'fw' is not defined。如何定义第 24 行?
  • 使用fw = open('./result.txt','wb')
  • 哦,我得到了更好的结果,但仍然不完美。还是谢谢。
  • 当我尝试写入字节时,每个字节行后面都有一个新的空白行。
猜你喜欢
  • 2017-06-07
  • 2023-03-19
  • 1970-01-01
  • 2019-11-10
  • 2018-09-13
  • 2016-11-26
  • 2020-12-03
  • 2018-04-12
  • 1970-01-01
相关资源
最近更新 更多