2012-06-21 54 views
4

所以我是新的python,我非常需要帮助。在url中传递变量?

我有一个文件,它有一堆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并持续显示值..有没有办法做到这一点?

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

回答

10

旧风格的字符串连接可以用来

>>> 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() 
+0

+1剥换行。 – SuperSaiyan

+0

非常感谢你帮助我。我现在正面临一个新问题。假设我尝试使用say,只是少数id来读取文本文件,它在执行时没有问题。但是我从我正在阅读ID的文本文件中有很多。代码无法执行。这是什么原因?有没有办法解决这个问题? – user1452759

+0

@ user1452759:你得到的错误是什么?从那里开始会很好。即使您有很多ID,解决方案也应该可以工作。很有可能并非所有的url获取都会返回可以加载到json中的数据 – pyfunc

2

懒人风格:

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 
1

您需要做的第一件事就是知道如何从文件中读取每一行。首先,你必须打开文件;你可以用一个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 
+0

非常感谢你帮助我。我现在正面临一个新问题。假设我尝试使用say,只是少数id来读取文本文件,它在执行时没有问题。但是我从我正在阅读ID的文本文件中有很多。代码无法执行。这是什么原因?有没有办法解决这个问题? – user1452759

+0

你能发布错误信息吗?如果不知道问题是什么,很难说。 –