避免Cookie过期(网页抓取)

时间:2018-09-01 15:08:00

标签: python-3.x cookies web-scraping beautifulsoup python-requests

因此,我正在使用Python为学校的成绩单网站Schoology制作一个网络抓取工具。到目前为止,它的效果很好,但是让我感到困扰的是,所有cookie都将在几天后过期。有没有一种方法可以自动获取新的cookie,这样我就不必每隔几天更换一次它们?我的学校使用“ SSO”登录名,您必须使用学校的Google帐户登录,这使事情变得复杂。我使用CURL来获取标题/ cookie信息。如果我在代码中还有其他需要改进的地方,请告诉我。这是我的代码:

# Schoology Web Scraper

import requests
from bs4 import BeautifulSoup

grades = []

headers = {
    # A bunch of headers / cookies that will expire
}

response = requests.get('https://monongalia.schoology.com/grades/grades', headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

for item in soup.find_all('span', attrs={"class":"course-grade-value"}):
  grades.append(item.get_text())

print('\n'.join(grades))

1 个答案:

答案 0 :(得分:0)

您可以让它通过登录并使用您可以使用的用户提供的凭据:

from bs4 import BeautifulSoup
import requests

##################

username=""
password=""
schoolID=""

##################

# ^ fill in these values ^

payload = {
"mail":username
"pass":password
"school_nid":
}

session = requests.Session()
response = session.post('https://monongalia.schoology.comlogin/ldap', data = payload)
# this will log you in using the credentials provided above

# continue with script below, all cookies will be saved without you needing to do 
# anything

将用户名和密码作为有效内容发送到url,使用Session()它将保留 整个脚本中的Cookie,因此您无需手动收集它们