【问题标题】:Unable to scrape csrf token (available in page source) from a webpage using requests无法使用请求从网页中抓取 csrf 令牌(在页面源中可用)
【发布时间】:2021-04-28 12:38:11
【问题描述】:

我正在尝试从网站上抓取 csrf 令牌。但是,即使页面源中的令牌可用,我创建的脚本也会惨遭失败。这是site url

我试过了:

import requests
from bs4 import BeautifulSoup

url = 'https://fanniemae.mbs-securities.com/fannie/search?issrSpclSecuType=Super&status=Active'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    r = s.get(url)
    soup = BeautifulSoup(r.text,"lxml")
    csrf = soup.select_one("[name='_csrf']").get("content")
    print(csrf)

如何使用请求从该站点刮取 csrf 令牌?

【问题讨论】:

  • r.text 是否符合您的预期?
  • 那么print(csrf)的输出是什么?
  • 当我测试您的代码时,我收到了“状态代码 500”。您是否能够获得此 url 请求的“状态代码 200”?

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


【解决方案1】:

这里的技巧是在标题中包含Accept 键和值以获得所需的响应。这就是我使用请求从该站点获取表格内容的方式:

import requests
from bs4 import BeautifulSoup

url = 'https://fanniemae.mbs-securities.com/fannie/search?issrSpclSecuType=Super&status=Active'
link = 'https://fanniemae.mbs-securities.com/api/search/fannie'
params = {
    'issrSpclSecuType': 'Super',
    'status': 'Active',
    'page': 1,
    'max_results': 100,
    'sortField': 'cusip',
    'sortAsc': 'true'
}
with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
    s.headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
    r = s.get(url)
    soup = BeautifulSoup(r.text,"lxml")
    s.headers['x-csrf-token'] = soup.select_one("[name='_csrf']")["content"]
    s.headers['referer'] = 'https://fanniemae.mbs-securities.com/fannie/search?issrSpclSecuType=Super&status=Active'
    res = s.get(link,params=params)
    for item in res.json():
        print(item['cusip'])

【讨论】:

    猜你喜欢
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-11
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多