首页 > 解决方案 > 试图用一个 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>

标签: cookiesweb-scrapingbeautifulsouppython-requestshtml-parsing

解决方案


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'
}

推荐阅读