Created
October 7, 2015 06:14
-
-
Save algotrader-dotcom/a8da18d7b936434673e9 to your computer and use it in GitHub Desktop.
[Python] Extract all links from a web page
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/env python | |
# get_links.py | |
import re | |
import sys | |
import urllib | |
import urlparse | |
from BeautifulSoup import BeautifulSoup | |
class MyOpener(urllib.FancyURLopener): | |
version = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15' | |
def process(url): | |
myopener = MyOpener() | |
#page = urllib.urlopen(url) | |
page = myopener.open(url) | |
text = page.read() | |
page.close() | |
soup = BeautifulSoup(text) | |
for tag in soup.findAll('a', href=True): | |
tag['href'] = urlparse.urljoin(url, tag['href']) | |
print tag['href'] | |
# process(url) | |
def main(): | |
if len(sys.argv) == 1: | |
print "Jabba's Link Extractor v0.1" | |
print "Usage: %s URL [URL]..." % sys.argv[0] | |
sys.exit(-1) | |
# else, if at least one parameter was passed | |
for url in sys.argv[1:]: | |
process(url) | |
# main() | |
if __name__ == "__main__": | |
main() | |
# https://pythonadventures.wordpress.com/2011/03/10/extract-all-links-from-a-web-page/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment