python - 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 网站的权限,因为测试其他网站工作正常。
解决方案
我尝试了您的尝试 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
标头更改为典型的内容。
推荐阅读
- c - 为什么 stddef 中的 size_t 而不是 stdint?
- amazon-web-services - AWS 线索者 - 了解内部负载均衡器和入口
- r - 根据行号为列表中各种数据框的行分配值
- c# - Linq 邮编问题
- angular - 如何仅显示微调器激活的文本框Angular 4
- ionic-framework - 带有条纹和 woocommerce-api 的 Ionic 3
- javascript - 显示的日期不正确
- sass - 尝试编译 SASS 代码时出错
- python - python pandas groupby排序排名/前n
- powershell - 定义要在批处理脚本中使用的变量