【发布时间】: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