首页 > 解决方案 > Python 请求:无权访问 URL 和 unicode 错误

问题描述

我的目标是爬取 macys.com 网站,但我无法访问。以下代码是我最初的尝试。

尝试 1

from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.macys.com').text
soup = BeautifulSoup(source, 'lxml')

print(soup)

这导致了以下错误。

<html><head>
<title>Access Denied</title>
</head><body>
<h1>Access Denied</h1>
You don't have permission to access the requested URL on this server.
<p>Reference: 18.c503d417.1587673952.4f27a98</p>
</body>
</html>

在 stackoverflow 上找到类似问题后,我看到最常见的解决方案是添加标题。这是该尝试的主要代码。

尝试 2

url = 'https://www.macys.com'
headers = {'User-agent': 'Mozilla/5.0'}

res = requests.get(url, headers=headers)

soup = BeautifulSoup(res.content, 'lxml')

print(soup)

这是我收到的最后一条错误消息。在研究了该网站之后,我仍然不确定如何进行。

UnicodeEncodeError: 'charmap' codec can't encode character '\x92' in position 586833: character maps to <undefined>

我非常介绍水平,所以我很欣赏任何见解。我也真的很好奇为什么我没有 macys 网站的权限,因为测试其他网站工作正常。

标签: pythonweb-scrapingunicodebeautifulsouppython-requests

解决方案


我尝试了您的尝试 2代码,它对我来说很好。

尝试将 BeautifulSoup 的from_encoding参数设置为utf-8,如下所示:

url = 'https://www.macys.com'
headers = {'User-agent': 'Mozilla/5.0'}

res = requests.get(url, headers=headers)

soup = BeautifulSoup(res.content, 'lxml', from_encoding='utf-8')

print(soup)

我也真的很好奇为什么我没有 macys 网站的权限,因为测试其他网站工作正常。

这是梅西百货的管理员为防止机器人访问他们的网站而采取的措施。不过,这是一种极其微不足道的保护形式,因为您只需要将user-agent标头更改为典型的内容。


推荐阅读