我正试图从一个网站上用一个漂亮的图书馆刮取一些定居点的名字。该网站使用'windows-1250'字符集,但有些字符显示不正确。请看定居点的姓,应该是Župkov。你知道吗
你能帮我解决这个问题吗? 代码如下:
# 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)
我使用的是python3.5.1和beautifulsoup4.4.1。你知道吗
服务器可能会发送有关
UTF-8
的HTTP头信息,但HTML使用Win-1250
。所以requests
使用UTF-8
来解码数据。你知道吗但是您可以获得原始数据
source_code.content
,并使用decode('cp1250')
来获得正确的字符。你知道吗或者您可以在获得
text
之前手动设置encoding
您还可以在
BS
中使用原始数据source_code.content
,因此它应该使用有关编码的HTML信息看到了吗
因为您知道站点的编码,所以只需将其显式传递给带有响应内容的BeautifulSoup构造函数,而不是文本:
问题不在于beautifulsoup,它只是无法确定您使用的是什么编码(请尝试
print('encoding', obce_soup.original_encoding)
),而这是由于您将其处理为Unicode而不是字节造成的。你知道吗如果您尝试这样做:
要创建beautifulsoup对象,您将看到它现在正确编码,输出正常。你知道吗
相关问题 更多 >
编程相关推荐