在url中传递变量?

2024-03-28 22:01:35 发布

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

所以我是python新手,急需帮助。

我有一个文件,里面有一堆的id(整数值)写在里面。它是一个文本文件。

现在我需要将文件中的每个id传递到一个url中。

例如“https://example.com/[id]”

会这样做的

A = json.load(urllib.urlopen("https://example.com/(the first id present in the text file)"))
print A

它的基本功能是读取上面url中存在的id的某些信息并显示出来。我希望它以循环格式工作,在循环格式中,它将读取文本文件中的所有id,并将其传递到“a”中提到的url并连续显示值..有方法这样做吗?

如果有人能帮我,我将非常感激!


Tags: 文件thehttpscomidjsonurlexample
3条回答

可以使用旧式字符串连接

>>> id = "3333333"
>>> url = "https://example.com/%s" % id
>>> print url
https://example.com/3333333
>>> 

新样式字符串格式:

>>> url = "https://example.com/{0}".format(id)
>>> print url
https://example.com/3333333
>>> 

avasal中提到的文件的读取进行了少量更改:

f = open('file.txt', 'r')
for line in f.readlines():
    id = line.strip('\n')
    url = "https://example.com/{0}".format(id)
    urlobj = urllib.urlopen(url)
    try:
        json_data = json.loads(urlobj)
        print json_data
    except:
        print urlobj.readlines()

你需要做的第一件事是知道如何从文件中读取每一行。首先,必须打开文件;可以使用with语句来完成此操作:

with open('my-file-name.txt') as intfile:

这将打开一个文件并将对该文件的引用存储在intfile中,它将在with块的末尾自动关闭该文件。然后需要读取文件中的每一行;可以使用常规的for循环来执行此操作:

  for line in intfile:

这将遍历文件中的每一行,一次读取一行。在循环中,您可以以line的形式访问每一行。剩下的就是使用你给出的代码向你的网站提出请求。您丢失的一位是所谓的“字符串插值”,它允许您用其他字符串、数字或任何其他东西格式化字符串。在您的例子中,您希望将一个字符串(来自文件的行)放入另一个字符串(URL)中。为此,可以使用%s标志和字符串插值运算符%

url = 'http://example.com/?id=%s' % line
A = json.load(urllib.urlopen(url))
print A

综合起来,你会得到:

with open('my-file-name.txt') as intfile:
  for line in intfile:
    url = 'http://example.com/?id=%s' % line
    A = json.load(urllib.urlopen(url))
    print A

懒惰风格:

url = "https://example.com/" + first_id

A = json.load(urllib.urlopen(url))
print A

旧风格:

url = "https://example.com/%s" % first_id

A = json.load(urllib.urlopen(url))
print A

新款2.6+:

url = "https://example.com/{0}".format( first_id )

A = json.load(urllib.urlopen(url))
print A

新款2.7+:

url = "https://example.com/{}".format( first_id )

A = json.load(urllib.urlopen(url))
print A

相关问题 更多 >