cookies - 试图用一个 cookie 抓取页面
问题描述
我正在尝试从URL中抓取表格。我已经使用 requests 库有一段时间了,还有漂亮的汤,但我不想冒险使用网络驱动程序,因为我以前一直在走这条路。
所以我提出了一个请求,并阅读了响应。但我在标题中得到以下内容,没有别的。有人可以向我解释我需要做什么(整个上午都花在这上面并开始失去情节)?
<head>
<meta charset="utf-8">
<title>SoccerSTATS.com - cookie consent</title>
<style>
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 18px;
margin: 4px 2px;
cursor: pointer;
}
.button1 {padding: 10px 24px;}
.button2 {padding: 12px 28px;}
.button3 {padding: 14px 40px;}
.button4 {padding: 32px 16px;}
.button5 {padding: 16px;}
</style>
<script type="text/javascript">
function setCookielocal(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
var originpage = "/team.asp?league=england_2018&stats=20-bournemouth";
document.cookie = cname + "=" + cvalue + "; " + expires;
window.location = "//www.soccerstats.com" + originpage;
}
</script>
</head>
解决方案
User-Agent 请求标头包含一个特征字符串,允许网络协议对等方识别请求软件用户代理的应用程序类型、操作系统、软件供应商或软件版本。在服务器端验证 User-Agent 标头是一种常见操作,因此请务必使用有效浏览器的 User-Agent 字符串以避免被阻止。
(来源: http: //go-colly.org/articles/scraping_related_http_headers/)
您唯一需要做的就是设置一个合法的用户代理。因此添加标题来模拟浏览器。:
# This is a standard user-agent of Chrome browser running on Windows 10
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
}
例子:
from bs4 import BeautifulSoup
import requests
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'}
resp = requests.get('http://example.com', headers=headers).text
soup = BeautifulSoup(resp, 'html.parser')
此外,您可以添加另一组标头来伪装成合法浏览器。添加更多这样的标题:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language' : 'en-US,en;q=0.5',
'Accept-Encoding' : 'gzip',
'DNT' : '1', # Do Not Track Request Header
'Connection' : 'close'
}
推荐阅读
- javascript - Javascript从二进制数据下载不完整/损坏的文件创建blob
- c# - Xamarin Forms 如何将 ContentPage 注入 Frame 元素?
- ruby-on-rails - 过滤后获取所有关联记录
- blazor - Blazer 服务器:设置 Braintree Payment Javascript 和 .NET SDK 和 API
- kubernetes - kubernetes 是否会重新调整 pod 以利用资源?
- vim - vim 失去颜色方案切换语法
- neural-network - 是否可以加载使用 model.module.state_dict() 存储但使用 model.state_dict() 加载的模型
- c - 寻找辅因子矩阵
- razor - 来自项目列表的 google.visualization.AnnotatedTimeLine
- kubernetes - 不会过期的 Vault 令牌