python-scripts/09_basic_link_web_crawler.py

34 lines
554 B
Python
Raw Normal View History

2014-05-18 16:29:23 +02:00
import requests
import re
import urlparse
# regex
link_re = re.compile(r'href="(.*?)"')
2014-05-18 20:16:56 +02:00
def crawl(url):
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
req = requests.get(url)
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
# Check if successful
if(req.status_code != 200):
return []
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
# Find links
links = link_re.findall(req.text)
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
print "\nFound {} links".format(len(links))
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
# Search links for emails
for link in links:
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
# Get an absolute URL for a link
link = urlparse.urljoin(url, link)
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
print link
2014-05-18 23:36:36 +02:00
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
if __name__ == '__main__':
crawl('http://www.realpython.com')
2014-05-18 23:36:36 +02:00