Created
March 2, 2017 08:51
-
-
Save rathankalluri/b7b7efb02ce1256449a1dd634e3875c5 to your computer and use it in GitHub Desktop.
Get URLs from a page - Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import urllib | |
def get_page(url): | |
if(url): | |
return urllib.urlopen(url).read() | |
else: | |
return '' | |
def get_next_url(page): | |
pre_link = page.find('<a href=') | |
if pre_link == -1: | |
return None,0 | |
pre_quote = page.find('"',pre_link) | |
post_quote = page.find('"', pre_quote+1) | |
url = page[pre_quote+1:post_quote] | |
return url, post_quote | |
def print_all_pages(page): | |
while True: | |
url, endpos = get_next_url(page) | |
if url: | |
if url.find('http') == 0: | |
print url | |
page = page[endpos:] | |
else: | |
break | |
print_all_pages(get_page('http://xkcd.com/353')) #Dynamically pass a page here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment