我試圖寫一個代碼來使用Python3網站抓住一些數據,你可以從代碼中看到:Python的BS4打印寫入錯誤
from bs4 import BeautifulSoup
import urllib.request
import sys
headers={}
headers['User-Agent']="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36"
req=urllib.request.Request('http://www.cjcyw.com/a/chuanbodangan/2015/0930/47853.html',headers=headers)
resp=urllib.request.urlopen(req)
xml=BeautifulSoup(resp,'html.parser')
x=xml.findAll('dd')
for item in x:
item=item.text.encode('utf-8')
print(sys.stdout.buffer.write(item))
的結果是這樣的:
當我把這些數據寫入到一個txt文件:
我使用STR調試,真正的問題是蹦出:
在4.txt文件中顯示數字,但不是我想要的結果。 –
你爲什麼使用'sys.stdout.buffer.write'?嘗試'f.write(item)'。 –
我不認爲這裏需要'.encode()'。 –