首页 > 解决方案 > 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

任何想法如何解决这个问题?

标签: pythonweb-scraping

解决方案


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

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

是:

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

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


推荐阅读