Python:beauthoulsoup的输出有错误的编码

2024-10-03 13:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个编码问题,当一个响应被放入beautifulsoup时。 响应的可读输出以正确的方式格式化,如Artikelstandort: Österreich,但在运行beautifulGroup之后,它将被转换为Artikelstandort: Österreich。我将为您提供更改的代码:

def formTest (browser, formUrl, cardName, edition):
   browser.open (formUrl)

   data = browser.response().read()
   with open ('analyze.txt', 'wb') as textFile:
      print 'wrinting file'
      textFile.write (data)

   #BS4 -> need from_encoding
   soup = BeautifulSoup (data, from_encoding = 'latin-1')
   soup = soup.encode ('latin-1').decode('utf-8')
   table = soup.find('table', { "class" : "MKMTable specimenTable"})

数据有正确的数据,编码错误。我在soup上尝试了各种编码/解码,但没有得到任何工作结果。在

我从中提取数据的页面是:https://www.magickartenmarkt.de/Mutilate_Magic_2013.c1p256992.prod

编辑: 我用prettify如建议的那样更改了编码,但现在我面临以下错误:

TypeError: slice indices must be integers or None or have an __index__ method

变漂亮了什么?我绘制了新的输出,表仍然在“”(<table class="MKMTable specimenTable">)中

编辑2:

新错误为:

在:soup.encode ('latin-1').decode('utf-8')

错误:UnicodeDecodeError: 'utf8' codec can't decode byte 0xfc in position 518: invalid start byte

如果我使用编码和编码,解码其他字节时会出错。在


Tags: 数据frombrowser编码data错误tableopen
1条回答
网友
1楼 · 发布于 2024-10-03 13:21:54

您现在可能不需要解决方案,但如果有人在这里停留,您应该这样做:
您可能应该对data而不是soup使用编码过程。
我通常要做的是使用requests库来获得原始响应,然后使用'response.text'这样的语法获取文本内容,然后使用response.encoding='utf-8'强制编码。
至少,我给响应.text到BeautifulSoup()

相关问题 更多 >