简体   繁体   中英

'utf-8' codec can't decode byte 0xf6 in position 139604: invalid start byte

I am making a knowledge engineering project.

When I was crawling some scientists personal site, this bug occurred.

import html2text
import requests
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import urllib


homepage = "http://angom.myweb.cs.uwindsor.ca"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
req = urllib.request.Request(url=homepage, headers=headers)
print(req)
c = urlopen(req).read()
print(type(c))

content = urlopen(req).read().decode("utf-8")

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 139604: invalid start byte

The encoding in the page header states:

<meta http-equiv=Content-Type content="text/html; charset=windows-1252">

.. so use that when decoding the string.

content = urlopen(req).read().decode("windows-1252")

will work in this instance.

If you are planning to use BeautifulSoup, it already does a really good job figuring out the encoding .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM