0

I have to open several websites to check something. The only difference between the links to every page is an id which I have stored in a CSV file. I want to iterate through the CSV file and replace the id for every website.

I want to do it with the replace statement and change the xxx in the link. But it does ́nt change the id and tries to open the link with the xxx several times.

import webbrowser
import csv
link = "https://website.com/de/tour/xxx/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
 reader = csv.reader(f)
 for row in reader:
 print(row)
 link.replace("xxx", str(row))
 webbrowser.open(link)
 print(link)
 link = "https://website.com/de/tour/xxx/geometrie.html"
Alexander
111k32 gold badges212 silver badges208 bronze badges
asked Aug 11, 2016 at 7:33

3 Answers 3

1

str.replace returns a new string, so you will have to catch it:

link = link.replace("xxx", str(row))

Although it will be better to use a "template" url instead of reassigning link to the url with the xxx in every iteration. An example of having a template url and using format to create the required url:

import webbrowser
import csv
basic_url = "https://website.com/de/tour/{}/geometrie.html"
with open('spielbergList.csv', 'rb') as f:
 reader = csv.reader(f)
 for row in reader:
 print(row)
 webbrowser.open(basic_url.format(row))
answered Aug 11, 2016 at 7:40
Sign up to request clarification or add additional context in comments.

Comments

0

the replace method of a string returns a new string and doesn't modify the old one in place so you have to catch the new string in another variable or re-use your link variable

link = link.replace("xxx", str(row))

The reason for this, is that strings are immutable (you can't modify them after creation)

>>> a = 'hello world'
>>> a.replace('hello', 'hi')
'hi world'
>>> a # a is still hello world
'hello world'
>>> a = a.replace('hello', 'hi')
>>> a
'hi world'
>>> 
answered Aug 11, 2016 at 7:37

Comments

0

You can also use format.

for row in reader:
 webbrowser.open('https://website.com/de/tour/{0}/geometrie.html'.format(row))
answered Aug 11, 2016 at 7:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.