How do I insert a variable in the middle of the address that I pass to UrlLib2?

3

I'm using the urllib2 function in Python and I need to put a variable in the middle of the link that I pass to the function. For example:

request = urllib2.Request('https://api.stackexchange.com/2.2/users/id_user?order=desc&sort=reputation&site=stackoverflow')

Where id_user is a variable. How do I recognize id_user as a variable?

    
asked by anonymous 09.06.2014 / 14:19

2 answers

3

There are a few ways to do this.

Operator modulo % :

id_User = "IdUserNameAqui"
request = urllib2.Request('https://api.stackexchange.com/2.2/users/%s?order=desc&sort=reputation&site=stackoverflow' % id_User)

Operator unário + :

id_User = "IdUserNameAqui"
request = urllib2.Request('https://api.stackexchange.com/2.2/users/' + str(id_User) + '?order=desc&sort=reputation&site=stackoverflow')

Function str.format() :

id_User = "IdUserNameAqui"
request = urllib2.Request("https://api.stackexchange.com/2.2/users/{0}?order=desc&sort=reputation&site=stackoverflow".format(id_User))

Example

The example below will insert the contents of a variable in the middle of the URL, make the request, and get some information from the JSON returned.

import requests
#Para instalar: sudo pip install requests

id_User = "1"
url = "https://api.stackexchange.com/2.2/users/{0}?order=desc&sort=reputation&site=stackoverflow".format(id_User)
json = requests.get(url).json()

accountID  = json['items'][0]['account_id']
websiteURL = json['items'][0]['website_url']
userName   = json['items'][0]['display_name']

print ("ID: {0}\nNome de exibicao: {1}\nSite: {2}\n".format(accountID, userName, websiteURL))

# Saída
# ID: 1
# Nome de exibicao: Jeff Atwood
# Site: http://www.codinghorror.com/blog/
    
09.06.2014 / 15:25
0

Use the format () method.

id_user = 1
url = 'https://api.stackexchange.com/2.2/users/{0}?order=desc&sort=reputation&site=stackoverflow'
request = urllib2.Request(url.format(id_user))

You can use%, like this:

url = "...users/%s?order..." % id_user

It will work, but always prefer the format () method. As described by the official documentation , it handles common concatenation errors, and will be the official method used by Python from now on. The idea is that soon the% is no longer accepted.

You can also use "plus operation":

url = '...user/' + id_user + '?order...'

But it's a bad practice. When the code becomes larger (and you should always think about it), this url will be unreadable. If you need to join two strings quickly, you may want to use join ().

url = ''.join(['...user/',
               id_user,
               '?order...'])

In summary, use format () . That's what Python asks you to use, after all.

    
09.06.2014 / 15:59