有没有一种方法可以通过在Python中将网页转换成字符串来检索网页的HTML内容?

有没有一种方法可以通过在Python中将网页转换成字符串来检索网页的HTML内容?,python,web-scraping,urllib,Python,Web Scraping,Urllib,我试图检索网页的HTML内容,并将其解压缩,然后将其作为字符串读取。然而,我有一个问题,每当我运行代码时,我都会得到一个类似字节的对象,而不是一个字符串,decode()在这种情况下似乎不起作用 我的代码如下: money_request = urllib.request.urlopen('website-url-here').read() print(money_request.decode('utf-8') 运行上述脚本将产生以下错误: Traceback (most recent ca

我试图检索网页的HTML内容,并将其解压缩,然后将其作为字符串读取。然而,我有一个问题,每当我运行代码时,我都会得到一个类似字节的对象,而不是一个字符串,decode()在这种情况下似乎不起作用

我的代码如下:

money_request = urllib.request.urlopen('website-url-here').read()

print(money_request.decode('utf-8')
运行上述脚本将产生以下错误:

Traceback (most recent call last):
  File "E:\University Stuff\Licenta\gas_station_service.py", line 12, in <module>
    print(money_request.decode())
  File "C:\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u02bb' in position 143288: character maps to <undefined>
>>> 
回溯(最近一次呼叫最后一次):
文件“E:\University Stuff\Licenta\gas\u station\u service.py”,第12行,在
打印(money_request.decode())
文件“C:\Python38\lib\encodings\cp1252.py”,第19行,编码
返回codecs.charmap\u encode(输入、自身错误、编码表)[0]
UnicodeEncodeError:“charmap”编解码器无法对143288位置的字符“\u02bb”进行编码:字符映射到
>>> 
我还想指定,我已经使用Chrome控制台和命令document.characterSet检查了网站是否使用utf-8编码

我需要将其作为字符串检索,以便在代码行上执行搜索,从span标记中获取值


非常感谢您的帮助。

如果您使用漂亮的汤,可能会更好,因为它有助于解析为html 如果您没有在windows上安装此模块,如
pip install bs4
,如果在mac或linux上安装了
pip3 install bs4
,我希望python 3中已经存在请求,如果您没有lxml模块,请继续使用pip install安装

import requests
from bs4 import BeautifulSoup

res = request.get('website-url-here')
src = res.content
soup = BeautifulSoup(src, 'lxml')
markup = soup.prettify()
print(markup)
你会得到整个网页的刮削网页,这对你来说可能很容易 从中提取有用的 找到你想要的内容

soup.find_all('div', {'class', 'classname'})
这将返回到数组中,而这不会返回

soup.find('div', {'class', 'classname'})

但是这将返回第一个内容选择是你的

你可以简单地使用
文本
获取一个网站html代码字符串

import requests
response = requests.get('website-url-here')
print(response.text)

根据错误,
money\u request.decode('utf-8')
工作正常;尝试(通过调用
print
)对生成的
str
进行编码以在终端上显示失败。