将Urllib2与需要令牌的511 api一起使用

2024-04-20 04:01:41 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我只想向511api发送一个请求,并从火车站返回火车时刻。我可以使用完整的url请求来实现这一点,但是我希望能够设置值,而无需将一个字符串粘贴在一起,然后发送该字符串。我想让api返回不同车站的列车时刻。我看到其他使用头的请求,但我不知道如何将头与请求一起使用,并且对文档感到困惑。你知道吗

这很有效。。。你知道吗

urllib2.Request("http://services.my511.org/Transit2.0/GetNextDeparturesByStopCode.aspx?token=xxxx-xxx&stopcode=70142")
response = urllib2.urlopen(request)
the_page = response.read()

我希望能够像这样设置值。。。你知道吗

token = xxx-xxxx
stopcode = 70142
url = "http://services.my511.org/Transit2.0/GetNextDeparturesByStopCode.aspx?"

。。。然后像这样把它们放在一起。。。你知道吗

urllib2.Request(url,token, stopcode)

得到同样的结果。你知道吗


Tags: 字符串orgtokenhttpurlresponserequestservice
2条回答

缺少的部分是“urllib”,需要与“urllib2”一起使用。具体来说,函数urllib.urlencode文件()返回值的编码版本。你知道吗

从urllib文档here

import urllib

query_args = { 'q':'query string', 'foo':'bar' }
encoded_args = urllib.urlencode(query_args)
print 'Encoded:', encoded_args

url = 'http://localhost:8080/?' + encoded_args
print urllib.urlopen(url).read()

因此,修正后的代码如下:

import urllib
import urllib2
token = xxx-xxxx
stopcode = 70142
query_args = {"token":token, "stopcode":stopcode}
encoded_args = urllib.urlencode(query_args)


request = urllib2.Request(url+encoded_args)
response = urllib2.urlopen(request)

print(response.read())

实际上,使用requests包要比使用urllib、urllib2容易上百万倍。以上所有代码都可以替换为:

import requests
token = xxx-xxxx
stopcode = 70142
query_args = {"token":token, "stopcode":stopcode}
r = request.get(url, params = query_args)
r.text

string formatting文档将是一个很好的开始学习更多关于插入值的不同方法的地方。你知道吗

val1 = 'test'
val2 = 'test2'
url  = "https://www.example.com/{0}/blah/{1}".format(val1, val2)

urllib2.Request(url)

相关问题 更多 >