Created
September 14, 2011 17:04
-
-
Save chrisguitarguy/1217107 to your computer and use it in GitHub Desktop.
Get specific links from a page using python and BeautifulSoup
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
from BeautifulSoup import BeautifulSoup as Soup | |
from urllib2 import urlopen | |
def get_product_links(url): | |
try: | |
content = urlopen(url).read() | |
except: | |
return False | |
soup = Soup(content) | |
products = soup.findAll('h2', {'class': 'product-name'}) | |
links = [] | |
for p in products: | |
try: | |
a = p.find('a')['href'] | |
except: | |
continue | |
else: | |
links.append(a) | |
return links | |
if __name__ == '__main__': | |
from sys import argv, exit | |
if len(argv) < 3: | |
print 'usage: %s URL output_file' % argv[0] | |
exit() | |
else: | |
links = get_product_links(argv[1]) | |
out = open(argv[2], 'w') | |
if not out: | |
print "error!" | |
exit() | |
for link in links: | |
out.write(link + '\n') | |
out.close() | |
exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment