1

i have a redirection url

www.test.com

it will redirect me to

www.test.com/XXYYXXYY

ans every time when i open it will redirect me to a new url ( XXYYXXYY will change every time )

so i want to save them into a CSV file

import urllib2
import csv
import sys

url = 'http://www.test.com'

u = urllib2.urlopen(url)
localFile = open('file.csv', 'w')
localFile.write(u.read())
localFile.close()

is this a correct code ?

thank you

2
  • What are you trying to save? The contents of the site or the unique URL? What happens when you run the code? Does it work the way you expect it? If so, then it's (more or less) correct. I would just change to with open('file.csv', 'w') as localFile: Commented Jul 9, 2013 at 11:01
  • brandon ( every final url will give me a unique code so i want to save the url then i can save the part of the code for example: www.test.com will redirect to www.test.com/XXXXYYYY i want to save the final url then i can delete the ( www.test.com ) to get just the code ( XXXXYYYY ) Commented Jul 9, 2013 at 11:21

1 Answer 1

1

geturl() will give you the final URL

import urllib2
import csv
import sys

url = 'http://www.test.com'

u = urllib2.urlopen(url)
localFile = open('file.csv', 'w')
localFile.write(u.geturl())
localFile.close()
Sign up to request clarification or add additional context in comments.

8 Comments

ton1c thank you so much i tried your code but nothing happened! ( there is no csv file ! ) see my code below import urllib2 import csv import sys url = 'test.com' u = urllib2.urlopen(url) localFile = open('C:\test\file.csv', 'w') localFile.write(u.geturl()) localFile.close() and why it won't work ? sorry i'm beginner
Your location of the file is wrong. To create file use this C:\\test\\file.csv as file location. To create CSV correctl use CSV library: writer = csv.writer(localfile) writer.writerow(u.geturl())
thank you so much it's working now !! but there are 2 problems 1-every letter or number takes 1 cell ( i want the whole url in 1 cell ) 2-if i run the script 2 times it will delete the first url and save the new one ( i want to save all the urls and every url takes 1 cell )
hi ton1c i finally know how to put the whole url into 1 cell by this code writer.writerow([u.geturl()]) but the second problem i don't know how to solve it ( i mean how to save the urls instead of removing the old url and replace it with a new url )
Hi, use append to file. So instead of localFile = open('file.csv', 'w') use localFile = open('file.csv', 'a')
|

Your Answer

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.