python-3.x - BeautifulSoup 为某些站点返回 403 错误

标签 python-3.x beautifulsoup http-status-code-403

我不明白为什么我会收到其中一些网站的 403 错误。

如果我手动访问 URL,页面加载正常。除了 403 响应之外没有任何错误消息,所以我不知道如何诊断问题。

from bs4 import BeautifulSoup
import requests    

test_sites = [
 'http://fashiontoast.com/',
 'http://becauseimaddicted.net/',
 'http://www.lefashion.com/',
 'http://www.seaofshoes.com/',
 ]

for site in test_sites:
    print(site)
    #get page soure
    response = requests.get(site)
    print(response)
    #print(response.text)

运行上述代码的结果是...

http://fashiontoast.com/

Response [403]

http://becauseimaddicted.net/

Response [403]

http://www.lefashion.com/

Response [200]

http://www.seaofshoes.com/

Response [200]

谁能帮我了解问题的原因和解决方案?

最佳答案

有时页面会拒绝未识别用户代理的 GET 请求。

使用浏览器 (Chrome) 访问页面。右键单击然后“检查”。复制 GET 请求的 User-Agent header (查看“网络”选项卡。

enter image description here

from bs4 import BeautifulSoup
import requests

with requests.Session() as se:
    se.headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
        "Accept-Encoding": "gzip, deflate",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language": "en"
    }


test_sites = [
 'http://fashiontoast.com/',
 'http://becauseimaddicted.net/',
 'http://www.lefashion.com/',
 'http://www.seaofshoes.com/',
 ]

for site in test_sites:
    print(site)
    #get page soure
    response = se.get(site)
    print(response)
    #print(response.text)

输出:

http://fashiontoast.com/
<Response [200]>
http://becauseimaddicted.net/
<Response [200]>
http://www.lefashion.com/
<Response [200]>
http://www.seaofshoes.com/
<Response [200]>

关于python-3.x - BeautifulSoup 为某些站点返回 403 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54154583/

相关文章:

python - 通过递归生成元素列表

asp.net - 如何使用 python 请求和 BeautifulSoup 在 Aspx 动态网站中循环下拉菜单并抓取数据

python - 如何使用 SEC 网站的 BeautifulSoup 的 getText() 方法忽略 HTML 中嵌入的 jpeg 图像数据

python - 使用 python selenium/Beautifulsoup 从多个页面提取数据

jquery - 如果 URL 在数据中,POST 返回 403

使用 "as"时,Python 循环引用导入不起作用

python名称错误名称未定义

python - 在 python 中定义一组(可能是分层的)常量的最佳方法是什么?

php - Apache 无法在 Raspberry Pi 上打开页面

chef-infra - Chef 客户端间歇性地抛出 403 禁止