0

我是 python 程序的新手。我想在谷歌趋势中获得热门话题。我如何从 python 发出这个 curl 请求

curl --data "ajax=1&htd=20131111&pn=p1&htv=l" http://www.google.com/trends/hottrends/hotItems

我尝试了以下代码

param = {"data" :"ajax=1&htd=20131111&pn=p1&htv=l"} 
value = urllib.urlencode(param)

req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
response = urllib2.urlopen(req)
result = response.read()
print result

但它没有返回预期值,这是当前谷歌的趋势。任何帮助,将不胜感激。谢谢。

4

2 回答 2

4

您误解了命令行data中的元素;curl那是已经编码的POST 正文,而您将其包装在另一个data密钥中并再次编码。

要么使用该值(而不是再次对其进行编码),要么将各个元素放入字典中并对其进行 urlencode:

value = "ajax=1&htd=20131111&pn=p1&htv=l"
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)

或者

param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'}
value = urllib.urlencode(param)
req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)

演示:

>>> import json
>>> import urllib, urllib2
>>> value = "ajax=1&htd=20131111&pn=p1&htv=l"
>>> req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
>>> response = urllib2.urlopen(req)
>>> json.load(response).keys()
[u'trendsByDateList', u'lastPage', u'summaryMessage', u'oldestVisibleDate', u'dataUpdateTime']
>>> param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'}
>>> value = urllib.urlencode(param)
>>> value
'htv=l&ajax=1&htd=20131111&pn=p1'
>>> req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value)
>>> response = urllib2.urlopen(req)
>>> json.load(response).keys()
[u'trendsByDateList', u'lastPage', u'summaryMessage', u'oldestVisibleDate', u'dataUpdateTime']
于 2014-09-17T15:52:58.410 回答
0

在 Python 中最容易使用该requests库。这是一个使用 Python 2.7 的示例:

import requests
import json

payload = {'ajax': 1, 'htd': '20131111', 'pn':'p1', 'htv':'l'}
req = requests.post('http://www.google.com/trends/hottrends/hotItems', data=payload)

print req.status_code # Prints out status code
print json.loads(req.text) # Prints out json data
于 2015-08-05T16:36:05.420 回答