简体   繁体   English

python中的卷曲请求

[英]Curl request in python

I'm a newbie to python program. 我是python程序的新手。 I want to get trending topics in google trends. 我想获取Google趋势中的趋势主题。 How do i make this curl request from python 我如何从python发出这个curl请求

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

I tried following code 我尝试了以下代码

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

But it is not returning expected values, which is the current Google trends. 但是它没有返回期望值,这是Google当前的趋势。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

You are misinterpreting the data element in your curl command line; 您在curl命令行中误解了data元素; that is the already encoded POST body, while you are wrapping it in another data key and encoding again. 这是已经编码的 POST正文,当您将其包装在另一个data密钥中并再次编码时。

Either use just the value (and not encode it again), or put the individual elements in a dictionary and urlencode that: 要么使用值(而不是再次对其进行编码),要么将各个元素放入字典中,并用urlencode进行编码:

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

or 要么

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)

Demo: 演示:

>>> 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']

Easiest using the requests library in Python. 在Python中使用requests库最简单。 Here's an example using Python 2.7: 这是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM