【问题标题】:How to send request to get JSON file如何发送请求以获取 JSON 文件
【发布时间】:2018-04-05 05:05:04
【问题描述】:

我试图从网站获取 json 文件。我尝试了 BeautifulSoup 库,但它是空的。

在 DevTools 中不为空并且有一个示例 Jquery 代码:

$('#domtableweek').dataTable({
       "processing": true,
       "serverSide": true,
       "bSort": false,
       "bLengthChange": false,
       "pageLength": 10,
       ajax: {
           url: '/data/mal-domains-data',
           type: 'POST',
           data: {'csrfmiddlewaretoken': 'yafh4aGjo0S6SeTci6qv2PzlcEuTW7E8', 'time':'7-Day'}
       },
       "dataSource": ''
   });

所以我尝试了这段代码

import requests

csrf = 'some_csrf_token'
cookie = 'some_cookie_id'
data = dict({'csrfmiddlewaretoken': 'yafh4aGjo0S6SeTci6qv2PzlcEuTW7E8', 'time':'7-Day'})
url = 'https://minotr.net/data/mal-domains' 
headers = {'Cookie':cookie}

r = requests.post(url, data=data, headers=headers)

print r.text

结果是:

 <p>You are seeing this message because this HTTPS site requires a &#39;Referer header&#39; to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p>
  <p>If you have configured your browser to disable &#39;Referer&#39; headers, please re-enable them, at least for this site, or for HTTPS connections, or for &#39;same-origin&#39; requests.</p>
`

你能帮帮我吗?

【问题讨论】:

    标签: jquery json python-2.7 python-requests


    【解决方案1】:

    所以问题是你需要在这里设置一个“Referer”标题。

    headers = {'Cookie':cookie, 'Referer':'https://google.com/'}
    

    试试这个

    要获取 JSON,您必须使用 .json() 方法。

    r = requests.post(url, data=data, headers=headers).json()
    

    【讨论】:

    • raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded
    • 这意味着您在没有 JSON 的情况下进入了错误的链接。如果您提出请求,它也会引发 403 错误,因此请检查您的设置,并可能设置另一个引用链接(您通常会从该链接进入您请求的页面)。
    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 2020-10-04
    • 2020-11-19
    • 2019-09-15
    • 2011-07-06
    • 2012-04-02
    • 2019-04-03
    相关资源
    最近更新 更多