python-3.x - 避免 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))
解决方案
您可以让它通过登录并使用您可以使用的用户提供的凭据:
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,因此您无需手动收集它们
推荐阅读
- c++ - Address Sanitizer:在遍历 shared_ptr 的映射并超出范围时自由崩溃后的堆使用
- azure - 具有主动-主动 Azure Sql Server 数据库复制
- python - 如何在 Python 中的两个其他子字符串之间获取子字符串
- r - 更改数据框的列名仅用于显示目的
- java - 将非 ISO 8601 解析为 ISO_INSTANT
- vba - 打开带有过滤器的报表
- r - 如何创建 Excel 数据透视表到 R
- css - 如何使我的离子输入与我的 ion-item 宽度相等
- flutter - 在 Flutter 中使用另一个嵌套模型的模型属性
- javascript - 可排序不会在 Safari 中拖动表格的所有列