【问题标题】:JSON POST request returns response in HTML not JSONJSON POST 请求以 HTML 而非 JSON 形式返回响应
【发布时间】:2018-11-03 05:22:22
【问题描述】:

我正在尝试使用 DOM 抓取网站,因此我认为最好的方法是通过请求向服务器发送发布请求,然后接收 JSON 响应。我可以在 Chrome 的 Inspect Element 工具中看到收到的响应,但在 python 中看不到。 这是我的代码,我得到的是整个页面的 HTML 响应,而不是我所追求的数据的 JSON 响应。

import requests
import json
url="https://www.umass.edu/peoplefinder/"

headers = {'content-type': 'application/json'}
searchData={'q': 'Alex'}
response=requests.post(url, data=json.dumps(searchData), headers=headers)
content = response.json()    
print(content)

我可以像这样在 Chrome 响应标签中获取数据。

{
    "ErrorHint": "",
    "ErrorCode": 0,
    "OverflowFlag": true,
    "Results": [{
    "Affil": ["Employee"],
    "Vcard": "/peoplefinder/vcard/xxxxxxxxxxx",
    "Title": "xxxxxxxxxxxx",
    "Phone": ["xxxxxxx"],
    "Dept": ["xxxxxxxxxxx"],
    "Building": ["xxxxxxxxxx"],
    "Email": "xxxxxxxxxxxx",
    "Name": "xxxxxxxxx"
}

关于如何在 python 中获取这个的任何想法?

【问题讨论】:

  • 导入 json,请参阅 json.loads () 和 json.load() 的示例,除非响应格式已正确。如果是,例如affil_0 = response["Results"][0][""Affil"] 可能会有所帮助。affil_0 将是一个列表。

标签: python json post web-scraping request


【解决方案1】:

你可以这样做。

import requests
url="https://www.umass.edu/peoplefinder/engine/"

headers = {'Accept': 'application/json, text/javascript, */*',
'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'q': 'Alex'}

s = requests.session()
response = s.post(url, data=payload, headers=headers)
print(response.json())

【讨论】:

  • 非常感谢,我终于让它工作了。此答案与其他答案一样正确。
【解决方案2】:

试试这个。它应该会为您获取所需的响应。

import requests

url = "https://www.umass.edu/peoplefinder/engine/"

headers = {
    'User-Agent': 'Mozilla/5.0',
    'Content-Type':'application/x-www-form-urlencoded'
}
response = requests.post(url, data={'q': 'Alex'}, headers=headers) 
print(response.json())

【讨论】:

  • 非常感谢,我终于让它工作了。此答案与其他答案一样正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2021-09-08
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多