【发布时间】:2020-02-12 15:14:02
【问题描述】:
第一次发布问题,我不是专家 python 或网络开发人员。
我正在创建一个网络抓取工具来抓取动态网页。我已经浏览了一些教程并整理了一个简单的 web scaper 以开始使用。它可以工作,因为它正在检索一些 json。但是,当检查 Chrome 开发工具中的响应时,我看到返回的 json 只是值为“null”的第一级。 我如何获得其余的值?
import requests
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "max-age=0, private, must-revalidate",
"origin": "https://www.example.com",
"referer": "https://www.example.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
}
#AJAX Request url from the Chrome dev tools
# data parameter taken from the Chrome dev tools, "Network Tab" >"Headers Tab" > "Request Payload"
r = requests.post('https://www.example.com/api/show', headers = headers,data = {"sort":"trending","page_num":4,"per_page":12,"q":"","tags":[]})
response = r.json()
print(response)
输出:
{'response':None}
预期的输出应该是:
{ "response":{ "discoverables":[ { "bullet_point":null,"category": "category_1","category_url":"/url"...
我在“网络”>“响应”下的 Chrome 开发工具中看到上述完整的 json 预期结果
我试过了:
- 更改标题值或省略它们,结果没有区别
- 尝试使用 GET(返回状态码 404)
- 使用 request.sessions
- 我试过只打印'r'而不使用.json,它返回
{"response":null}
不知道为什么其余的 json 没有被捕获。
我看了一下这里:http://toddhayton.com/2015/03/11/scraping-ajax-pages-with-python/ 但是,如他们的示例所示,没有“表单数据”。它改为显示“请求有效负载”,并且没有指定参数。
我假设我缺少一个参数来请求其余的 json 数据。或者与 POST 请求有关。如果需要更多信息,请告诉我。
【问题讨论】:
-
可能有很多内容...您可以发布您要抓取的页面吗?
-
indiegogo.com/explore/…我正在尝试抓取活动信息
-
我立即看到两件事,您需要在标题中包含 x-csrf-token,并将“data”更改为“json”。要获得有效的 x-csrf-token,您可能需要使用请求会话
-
我之前尝试过 x-csrf-token 标头/值,但没有成功。我将尝试使用会话并切换到 json。
-
谢谢!将“数据”更改为“json”并包括 x-csrf-token。不需要更改为会话。看起来需要更多阅读 requests 库。
标签: python json ajax web-scraping