Python requests. 403 Forbidden

I needed to parse a site, but i got an error 403 Forbidden. Here is a code:

url = 'http://worldagnetwork.com/'
result = requests.get(url)
print(result.content.decode())

Its output:

<html>
<head><title>403 Forbidden</title></head>
<body bgcolor="white">
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx</center>
</body>
</html>

Please, say what the problem is.

181842 次浏览

似乎该页面拒绝未标识 User-AgentGET请求。我用浏览器(Chrome)访问了该页面,并复制了 GET请求的 User-Agent头文件(查看开发工具的 Network 选项卡) :

import requests
url = 'http://worldagnetwork.com/'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
result = requests.get(url, headers=headers)
print(result.content.decode())


# <!doctype html>
# <!--[if lt IE 7 ]><html class="no-js ie ie6" lang="en"> <![endif]-->
# <!--[if IE 7 ]><html class="no-js ie ie7" lang="en"> <![endif]-->
# <!--[if IE 8 ]><html class="no-js ie ie8" lang="en"> <![endif]-->
# <!--[if (gte IE 9)|!(IE)]><!--><html class="no-js" lang="en"> <!--<![endif]-->
# ...

如果您是服务器的所有者/管理员,并且接受的解决方案不适合您,那么请尝试 禁用 CSRF 保护(链接到 SO 答案)

我使用的是 Spring (Java) ,因此安装程序要求您创建一个包含以下内容的 SecurityConfig.java文件:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure (HttpSecurity http) throws Exception {
http.csrf().disable();
}
// ...
}

Just add to Alberto's answer:

如果在添加 user-agent之后仍然得到 403 Forbidden,那么可能需要添加更多的标头,例如 referer:

headers = {
'User-Agent': '...',
'referer': 'https://...'
}

标题可以在开发工具的 Network > Headers > Request Headers中找到(按 F12切换)