首页 > 解决方案 > 避免 Cookie 过期(网页抓取)

问题描述

所以我正在使用 Python 为我学校的成绩册网站 Schoology 制作一个网络爬虫。到目前为止,它工作得很好,但我很烦恼地看到所有的 cookie 都会在几天后过期。有没有办法自动获取新的 cookie,这样我就不必每隔几天更换一次?我的学校使用“SSO”登录,您必须使用学校的谷歌帐户登录,这使事情变得有点复杂。我使用 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))

标签: python-3.xcookiesweb-scrapingbeautifulsouppython-requests

解决方案


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

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

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


推荐阅读