python - Python - TypeError:write() 参数必须是 str,而不是字节
问题描述
我收到来自 python 的错误消息。这是一个从牛津在线词典中提取音标的代码。
回溯(最后一次调用):文件“C:\Download\Oxford_PhoneticSymbol\Oxford_PhoneticSymbol.py”,第 24 行,在 fw.write((result + "\n").encode("utf-8")) 类型错误: write() 参数必须是 str,而不是 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
任何想法如何解决这个问题?
解决方案
将下载的页面保存到文件时出现此错误的解决方案:
TypeError: write() 参数必须是 str,而不是字节
是:
fw = open('./result.txt','wb')
二进制的“b”有所不同。
推荐阅读
- json - 如何在一个列上分组,在另一个列上聚合数组并创建一个由分组列键控的 JSON 对象
- javascript - 在android中创建地图活动时发生运行时错误
- mobile - 如何在 UWP 中将 Grid.Background 设置为 MediaPlayer?
- java - 返回类型泛型
- ios - 通过字符串 Xcode 标识符访问 UILabel
- cakephp - Cakephp 3.6 - 没有 mod_rewrite 的服务器上的 Auth 组件
- android - 打开带有地址和金额的比特币钱包的正确链接是什么?
- php - 如何处理向 Worker SQS [AWS] 发送消息的任务
- javascript - 从 iframe 内部想要获取所有 iframe 类名(每个 iframe 有不同的类名)
- javascript - 在反应中将数据添加到字典中