在Linux上从Bs4解码数据[重复]

Posted

技术标签:

【中文标题】在Linux上从Bs4解码数据[重复]【英文标题】:Decoding data from Bs4 on Linux [duplicate] 【发布时间】:2021-01-18 19:42:27 【问题描述】:

我正在尝试运行从here 获取一些数据的 Python 脚本。

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup


url = urllib.request.urlopen('http://database.ukrcensus.gov.ua/PXWEB2007/ukr/news/op_popul.asp')
soup = BeautifulSoup(url, 'html.parser')
print(soup)

它在 Mac 上运行得很好,但是当我尝试在 Linux 上运行它时,我得到了这样的输出:

<area  coords="2,5,21,26" href="../../index.htm" shape="rect" title="������� ��������"/>
<area  coords="43,6,62,26" href="../../ukr/help/web_map.asp" shape="rect" title="����� �����"/>
<area  coords="85,7,105,27" href="../../ukr/help/contact.asp" shape="rect" title="��������� ��'����"/>

我猜编码/解码有问题,但我无法真正弄清楚到底是什么。 提前致谢。

【问题讨论】:

似乎您缺少正确的字符集。您是否尝试过将其转换为 ASCII? 我该怎么做? ord()char() 不起作用 在 linux 上运行脚本可以正确打印字符。你的终端是什么?设置为显示 Unicode 字符? 问题是,它不只是在终端中。它还将未解码的字符加载到 sql 数据库中 如果不以明确的表示形式查看数据的实际内容(代表性的,理想情况下的小样本),我们就无法告诉您正确的编码;有问题的字节的十六进制转储,每边都有几个字节的上下文通常就足够了,特别是如果你能告诉我们你认为这些字节应该代表什么。另见meta.***.com/questions/379403/… 【参考方案1】:

您可以尝试使用选定的编码显式解码响应。例如:

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup

response = urllib.request.urlopen('http://database.ukrcensus.gov.ua/PXWEB2007/ukr/news/op_popul.asp')
html = response.read().decode('windows-1251')  # <--- explicitly decode the response using 'windows-1251' encoding
soup = BeautifulSoup(html, 'html.parser')
print(soup)

打印:

...

<map name="Map">
<area  coords="8,5,82,19" href="../../../../index.htm" shape="rect"/>
<area  coords="8,22,83,37" href="../../../../index.htm#" shape="rect"/>
<area  coords="8,39,83,56" href="../../../../index.htm#" shape="rect"/>
</map>
<map name="Map2">
<area  coords="2,5,21,26" href="../../index.htm" shape="rect" title="Головна сторінка"/>
<area  coords="43,6,62,26" href="../../ukr/help/web_map.asp" shape="rect" title="Карта сайту"/>
<area  coords="85,7,105,27" href="../../ukr/help/contact.asp" shape="rect" title="Зворотній зв'язок"/>
</map>
<map name="Map3">
<area coords="63,3,155,26" href="http://www.ukrcensus.gov.ua/index.php" shape="rect"/>
<area coords="65,25,162,44" href="http://www.ukrcensus.gov.ua/index.php" shape="rect"/>
</map>

【讨论】:

以上是关于在Linux上从Bs4解码数据[重复]的主要内容,如果未能解决你的问题,请参考以下文章

在服务器上从 xamarin 发布到 php 时出现问题 [重复]

ImportError:没有名为 bs4 的模块 [重复]

安装 pip install requests 和 pip install bs4 [重复]

如何以正确的方式编码和解码字符[重复]

UnicodeDecodeError:('utf-8'编解码器)在读取csv文件时[重复]

如何在 iOS 上从 Mapbox 解码“编码折线”