我的目标是清理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>
我很内向,所以我很欣赏任何见解。我还真的很好奇为什么我没有梅西网站的权限,因为测试其他网站效果很好
我尝试了你的尝试2代码,它对我来说效果很好
尝试将BeautifulSoup的
from_encoding
参数设置为utf-8
,如下所示:这是梅西百货的管理员为阻止机器人访问其网站所做的事情。不过,这是一种非常简单的保护形式,因为您只需要将
user-agent
头更改为一些典型的内容相关问题 更多 >
编程相关推荐