Python'请求'以错误的顺序添加参数

时间:2014-01-28 18:04:25

标签: python python-2.7 python-requests

import requests

endpoint = 'http://data.alexa.com/data?'
qparams = {'cli': 10,
           'url': 'www.google.com'}
response = requests.get(endpoint, params=qparams)

print response.url

这告诉我它看了http://data.alexa.com/data?url=www.google.com&cli=10

哪个网址错误,应为http://data.alexa.com/data?cli=10&url=www.google.com

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:14)

词典有没有固定顺序。如果您需要有序参数,请将参数作为(key, value)对序列传递:

qparams = (
    ('cli', 10),
    ('url', 'www.google.com'),
)

您还应该从网址?开始,requests将为您处理。

演示:

>>> import requests
>>> endpoint = 'http://data.alexa.com/data'
>>> qparams = (
...     ('cli', 10),
...     ('url', 'www.google.com'),
... )
>>> response = requests.get(endpoint, params=qparams)
>>> response.url
u'http://data.alexa.com/data?cli=10&url=www.google.com'
>>> print response.content
<?xml version="1.0" encoding="UTF-8"?>

<ALEXA VER="0.9" URL="google.com/" HOME="0" AID="=" IDN="google.com/">

<KEYWORDS>
<KEYWORD VAL="Mountain View"/>
</KEYWORDS><DMOZ>
<SITE BASE="google.com/" TITLE="Google" DESC="Enables users to search the world's information, including webpages, images, and videos. Offers unique features and search technology.">
<CATS>
<CAT ID="Top/Computers/Internet/Searching/Search_Engines/Google" TITLE="Search Engines/Google" CID="374822"/>
<CAT ID="Top/Regional/North_America/United_States/California/Localities/M/Mountain_View/Business_and_Economy/Industrial/Computers_and_Internet" TITLE="Industrial/Computers and Internet" CID="625367"/>
<CAT ID="Top/World/Français/Informatique/Internet/Recherche/Moteurs_de_recherche/Google" TITLE="Moteurs de recherche/Google" CID="247347"/>
<CAT ID="Top/World/Arabic/إقليمـي/الشرق_الأوسط/السعودية/تجارة_و_أقتصاد/كمبيوتر_و_إنترنت/محركات_بحث" TITLE="كمبيوتر و إنترنت/محركات بحث" CID="204954"/>
<CAT ID="Top/World/Español/Informática/Internet/Buscando_en_Internet/Motores_de_búsqueda" TITLE="Buscando en Internet/Motores de búsqueda" CID="29498"/>
</CATS>
</SITE>
</DMOZ>
<SD>
<POPULARITY URL="google.com/" TEXT="1" SOURCE="panel"/>
<REACH RANK="1"/>
<RANK DELTA="+0"/>
<COUNTRY CODE="US" NAME="United States" RANK="1"/>
</SD>
</ALEXA>