2016-11-27 15 views
2

BeautifulSoupライブラリを使用して、ウェブサイトからいくつかの名前の名前を掻き出しようとしています。このWebサイトでは、の「windows-1250」文字セットが使用されていますが、一部の文字は正しく表示されません。和解の姓を参照してください。これはŽupkovでなければなりません。BeautifulSoupを使用して文字を正しく表示できない

この問題を解決できますか? これはコードです:

# imports  
import requests 
from bs4 import BeautifulSoup 
from bs4 import NavigableString 

# create beautifulsoup object 
obce_url = 'http://www.e-obce.sk/zoznam_vsetkych_obci.html?strana=2500' 
source_code = requests.get(obce_url) 
plain_text = source_code.text 
obce_soup = BeautifulSoup(plain_text, 'html.parser') 

# define bs filter 
def soup_filter_1(tag): 
    return tag.has_attr('href') and len(tag.attrs) == 1 and isinstance(tag.next_element, NavigableString) 

# print settlement names 
for tag in obce_soup.find_all(soup_filter_1): 
    print(tag.string) 

私は、Python 3.5.1とbeautifulsoup 4.4.1を使用しています。

答えて

0

問題がbeautifulsoupではない、それはちょうどあなたが持っているものエンコードするかを決定することができない(してみてくださいprint('encoding', obce_soup.original_encoding))、これはバイトの代わりにUnicodeを渡すことによって発生します。

あなたはこれがしようとした場合:

obce_url = 'http://www.e-obce.sk/zoznam_vsetkych_obci.html?strana=2500' 
source_code = requests.get(obce_url) 
data_bytes = source_code.content # don't use .text it will try to make Unicode 
obce_soup = BeautifulSoup(data_bytes, 'html.parser') 
print('encoding', obce_soup.original_encoding) 

あなたbeautifulsoupオブジェクトを作成するために、あなたはそれが今エンコードの権利を取得し、あなたの出力がOKであることがわかります。

+0

あなたの答えをありがとう。それは期待どおりに働いた。 – user21816

0

おそらくサーバーはUTF-8についてのHTTPヘッダー情報を送信しますが、HTMLはWin-1250を使用します。したがってrequestsを使用してデータをデコードします。UTF-8

しかし、正しい文字を取得するにはオリジンデータsource_code.contentを使用し、decode('cp1250')を使用してください。

plain_text = source_code.content.decode('cp1250') 

それとも、あなたはまた、それが

obce_soup = BeautifulSoup(source_code.content, 'html.parser') 

を参照してくださいをコードに関するHTML情報を使用する必要があります BSsource_code.contentにoryginalデータを使用することができます text

source_code.encoding = 'cp1250' 

plain_text = source_code.text 

を取得する前に、手動でencodingを設定することができます

print(obce_soup.declared_html_encoding) 
+0

ありがとうございました。それはうまくいった。 – user21816

0

サイトのエンコーディングを知っているので、あなただけの応答の内容でBeautifulSoupコンストラクタに明示的に渡すことができ、テキストではなく:

source_code = requests.get(obce_url) 
content = source_code.content 
obce_soup = BeautifulSoup(content, 'html.parser', from_encoding='windows-1250') 
関連する問題