Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using variable in a url in python

Tags:

python

Sorry for this very basic question. I am new to Python and trying to write a script which can print the URL links. The IP addresses are stored in a file named list.txt. How should I use the variable in the link? Could you please help?

# cat list.txt

192.168.0.1
192.168.0.2
192.168.0.9

script:

import sys
import os

file = open('/home/list.txt', 'r')

for line in file.readlines():
    source = line.strip('\n')
    print source

link = "https://(source)/result”
print link

output:

192.168.0.1
192.168.0.2
192.168.0.9
https://(source)/result

Expected output:

192.168.0.1
192.168.0.2
192.168.0.9
https://192.168.0.1/result
https://192.168.0.2/result
https://192.168.0.9/result
like image 920
user3331975 Avatar asked May 28 '15 09:05

user3331975


People also ask

How do you pass a variable to the URL in Python?

How do you pass a parameter in a Python query? To send parameters in URL, write all parameter key:value pairs to a dictionary and send them as params argument to any of the GET, POST, PUT, HEAD, DELETE or OPTIONS request. then https://somewebsite.com/?param1=value1&param2=value2 would be our final url.


2 Answers

You need to pass the actual variable, you can iterate over the file object so you don't need to use readlines and use with to open your files as it will close them automatically. You also need the print inside the loop if you want to see each line and str.rstrip() will remove any newlines from the end of each line:

with open('/home/list.txt') as f:  
    for ip in f:
        print "https://{0}/result".format(ip.rstrip())

If you want to store all the links use a list comprehension:

with  open('/home/list.txt' as f:
    links = ["https://{0}/result".format(ip.rstrip()) for line in f]

For python 2.6 you have to pass the numeric index of a positional argument, i.e {0} using str.format .

You can also use names to pass to str.format:

with open('/home/list.txt') as f:
    for ip in f:
        print "https://{ip}/result".format(ip=ip.rstrip())
like image 58
Padraic Cunningham Avatar answered Oct 15 '22 08:10

Padraic Cunningham


Get the link inside the loop, you are not appending data to it, you are assigning to it every time. Use something like this:

file = open('/home/list.txt', 'r')

for line in file.readlines():
    source = line.strip('\n')
    print source
    link = "https://%s/result" %(source)
    print link
like image 27
shaktimaan Avatar answered Oct 15 '22 09:10

shaktimaan