中国語のテキストを抽出してファイルに書き込む際に問題があります。中国語のテキストをPythonでファイルに書き込む方法
str = "全球紧张致富豪财富缩水 贝索斯丁磊分列跌幅前两位";
f=open('test.txt','w');
f.write(str);
上記のコードは正常に動作します。ちょっとしたことを示す下のコードでファイルに書き込んでいます。
import requests;
from bs4 import BeautifulSoup
f=open('data.txt','w');
def techSinaCrawler():
url="http://tech.sina.com.cn/"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for li in soup.findAll('li',{'data-sudaclick': 'yaowenlist-1'}):
for link in li.findAll('a'):
href = link.get('href')
techSinaInsideLinkCrawler(href);
def techSinaInsideLinkCrawler(url):
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "html.parser")
for data in soup.findAll('h1',{'id': 'main_title'}):
str='main_title'+':'+ data.string
f.write(str);
f.write('\n');
techSinaCrawler();
のPython 2では、ヘルプ
使用している文字セットは何ですか? – Jay
ウェブサイトでUTF-8文字セットを使用 –
[This](https://stackoverflow.com/questions/20205455/how-to-correctly-parse-utf-8-encoded-html-to-unicode-strings-with- beautifulsoup)と[This(https://stackoverflow.com/questions/7219361/python-and-beautifulsoup-encoding-issues)は、BeautifulSoupのエンコーディングの問題を扱うのに役立つかもしれません。 – Ramon