在 Python 中发送 json 个请求

sending json requests in Python

我正在尝试发送一些 json 请求来抓取像这样 link 的无限滚动框。它的jsonlink是:

http://www.marketwatch.com/news/headline/getheadlines?ticker=XOM&countryCode=US&dateTime=12%3A00+a.m.+Nov.+8%2C+2016&docId=&docType=2007&sequence=6e09aca3-7207-446e-bb8a-db1a4ea6545c&messageNumber=1826&count=10&channelName=%2Fnews%2Fpressrelease%2Fcompany%2Fus%2Fxom&topic=&_=1479366266513

有些参数不是必须的,我创建了一个有效参数字典。例如,参数 Count 是每次滚动显示的项目数。我的代码是:

import json
import requests

parameters = {'countryCode':'US','dateTime':'', 'docId':'','sequence':'6e09aca3-7207-446e-bb8a-db1a4ea6545c', 
         'messageNumber':'1826','count':'10','channelName':'', 'topic':'_:1479366266513' }
data = json.dumps(parameters)
firstUrl = "http://www.marketwatch.com/investing/stock/xom"
html = requests.post(firstUrl, params = data).text 

我的问题是我无法根据参数发送请求,当我删除所有参数时,我得到相同的页面 (firstUrl link),就好像我包含了所有参数一样。您知道为什么会这样吗?我该如何解决这个问题?

params 需要一个 Python 字典,而不是字符串,所以你应该直接传递 parameters:

parameters = {'countryCode':'US','dateTime':'', 'docId':'','sequence':'6e09aca3-7207-446e-bb8a-db1a4ea6545c', 
         'messageNumber':'1826','count':'10','channelName':'', 'topic':'_:1479366266513' }

html = requests.post(firstUrl, parameters).text

此外,请确保您实际使用的是 post 而不是 get

我认为您使用的 firstUrl 不正确。此外,您应该使用 requests.get 而不是 post。您应该发送与 link.

中相同的参数
import json
import requests

parameters = {'ticker':'XOM', 'countryCode':'US','dateTime':'', 'docId':'','sequence':'6e09aca3-7207-446e-bb8a-db1a4ea6545c', 
         'messageNumber':'1826','count':'10','channelName':'', 'topic':'_:1479366266513' }
firstUrl = "http://www.marketwatch.com/news/headline/getheadlines"
html = requests.get(firstUrl, params = parameters)
print(json.loads(html.text)) # array of size 10