Python请求:没有访问URL的权限&unicode错误

2024-04-19 12:01:31 发布

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

我的目标是清理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>

我很内向,所以我很欣赏任何见解。我还真的很好奇为什么我没有梅西网站的权限,因为测试其他网站效果很好


Tags: 代码httpsimportcomsourceget网站www
1条回答
网友
1楼 · 发布于 2024-04-19 12:01:31

我尝试了你的尝试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)

I am also just genuinely curious why I don't have permissions for macys site as testing other sites works fine.

这是梅西百货的管理员为阻止机器人访问其网站所做的事情。不过,这是一种非常简单的保护形式,因为您只需要将user-agent头更改为一些典型的内容

相关问题 更多 >