python-scripts/09_basic_link_web_crawler.py

35 lines
616 B
Python
Raw Normal View History

2014-05-18 16:29:23 +02:00
import requests
import re
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
2014-05-18 16:29:23 +02:00
# 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
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 = urljoin(url, link)
2014-05-18 16:29:23 +02:00
print(link)
2014-05-18 16:29:23 +02:00
2014-05-18 20:16:56 +02:00
if __name__ == '__main__':
crawl('http://www.realpython.com')