對數據的提取和收集也是數據分析中一大重點,所以,學習爬蟲是非常有用的。完成數據採集,對後面的數據分析做下基礎。 今天,要介紹的是來自《Web Scraping With Python》中的一個示例——鏈接爬蟲。對於此類進行了簡單的總結,便於相互學習。 ...
對數據的提取和收集也是數據分析中一大重點,所以,學習爬蟲是非常有用的。完成數據採集,對後面的數據分析做下基礎。
今天,要介紹的是來自《Web Scraping With Python》中的一個示例——鏈接爬蟲。對於此類進行了簡單的總結,便於相互學習。
#! /usr/bin/env python # -*- coding:utf-8 -*- import re import urlparse import urllib2 import time from datetime import datetime import robotparser import Queue # 鏈接爬蟲 ''' 一個鏈接爬蟲需要考慮以下幾個問題: 1.下載網頁時,我們可能會遇到不可控制的錯誤,比如請求的網頁可能不存在。就要用到try和except語句,捕獲異常。 2.下載網頁時,我們也可能會遇上臨時性的錯誤,比如伺服器過載返回的503 Service Unavailable錯誤。就要多嘗試幾次下載。 3.一些網站可能會封殺預設的用戶代理,所以,我們應該重新設置一個用戶代理user_agent='wswp'。 4.下載網站鏈接時,應當考慮符合自己目標的鏈接,篩選出自己感謝的東西。通常用正則表達式來匹配這些鏈接。'<a[^>]+href=["\'](.*?)["\']'. 5.應當考慮網頁中的鏈接是什麼鏈接,如果是絕對鏈接就沒事,如果是相對鏈接就應該創建絕對鏈接。urlparse.urljoin() 6.爬取網頁的時候,經常會出現將要爬取的網頁中也有爬取過的鏈接,這樣會造成不斷迴圈。所以要建立一個URL管理器,管理爬取過的和未爬取的 7.所有爬蟲都應當遵守爬蟲協議(robots.txt),所以要引入robotparser模塊,以避免下載禁止爬取的URL 8.有時我們需要使用代理訪問某個網站。 9.如果我們爬取網站的速度過快,就會面臨被封禁或者伺服器過載的風險。所以應當在兩次下載之間添加延時。delay 10.有些網站中含有動態內容,如果爬取該網頁就會出現無限制的網頁,所以為了避免爬蟲陷阱,最好設置一個爬取深度(max_depth)——記錄到達當前網頁經過了多少鏈接。 ''' def link_crawler(seed_url, link_regex=None, delay=5, max_depth=-1, max_urls=-1, headers=None, user_agent='wswp', proxy=None, num_retries=1): """Crawl from the given seed URL following links matched by link_regex """ # the queue of URL's that still need to be crawled crawl_queue = Queue.deque([seed_url]) # the URL's that have been seen and at what depth seen = {seed_url: 0} # track how many URL's have been downloaded num_urls = 0 rp = get_robots(seed_url) throttle = Throttle(delay) headers = headers or {} if user_agent: headers['User-agent'] = user_agent while crawl_queue: url = crawl_queue.pop() # check url passes robots.txt restrictions if rp.can_fetch(user_agent, url): throttle.wait(url) html = download(url, headers, proxy=proxy, num_retries=num_retries) links = [] depth = seen[url] if depth != max_depth: # can still crawl further if link_regex: # filter for links matching our regular expression for link in get_links(html): if re.match(link_regex, link): links.extend(link) # links.extend(link for link in get_links(html) if re.match(link_regex, link)) for link in links: link = normalize(seed_url, link) # check whether already crawled this link if link not in seen: seen[link] = depth + 1 # check link is within same domain if same_domain(seed_url, link): # success! add this new link to queue crawl_queue.append(link) # check whether have reached downloaded maximum num_urls += 1 if num_urls == max_urls: break else: print 'Blocked by robots.txt:', url class Throttle: """Throttle downloading by sleeping between requests to same domain """ def __init__(self, delay): # amount of delay between downloads for each domain self.delay = delay # timestamp of when a domain was last accessed self.domains = {} def wait(self, url): domain = urlparse.urlparse(url).netloc last_accessed = self.domains.get(domain) if self.delay > 0 and last_accessed is not None: sleep_secs = self.delay - (datetime.now() - last_accessed).seconds if sleep_secs > 0: time.sleep(sleep_secs) self.domains[domain] = datetime.now() def download(url, headers, proxy, num_retries, data=None): print 'Downloading:', url request = urllib2.Request(url, data, headers) opener = urllib2.build_opener() if proxy: proxy_params = {urlparse.urlparse(url).scheme: proxy} opener.add_handler(urllib2.ProxyHandler(proxy_params)) try: response = opener.open(request) html = response.read() code = response.code except urllib2.URLError as e: print 'Download error:', e.reason html = '' if hasattr(e, 'code'): code = e.code if num_retries > 0 and 500 <= code < 600: # retry 5XX HTTP errors return download(url, headers, proxy, num_retries-1, data) else: code = None return html def normalize(seed_url, link): """Normalize this URL by removing hash and adding domain """ link, _ = urlparse.urldefrag(link) # remove hash to avoid duplicates return urlparse.urljoin(seed_url, link) def same_domain(url1, url2): """Return True if both URL's belong to same domain """ return urlparse.urlparse(url1).netloc == urlparse.urlparse(url2).netloc def get_robots(url): """Initialize robots parser for this domain """ rp = robotparser.RobotFileParser() rp.set_url(urlparse.urljoin(url, '/robots.txt')) rp.read() return rp def get_links(html): """Return a list of links from html """ # a regular expression to extract all links from the webpage webpage_regex = re.compile('<a[^>]+href=["\'](.*?)["\']', re.IGNORECASE) # list of all links from the webpage return webpage_regex.findall(html) if __name__ == '__main__': link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, user_agent='BadCrawler') link_crawler('http://example.webscraping.com', '/(index|view)', delay=0, num_retries=1, max_depth=-1, user_agent='GoodCrawler')