簡單爬蟲框架:
爬蟲調度器 -> URL管理器 -> 網頁下載器(urllib2) -> 網頁解析器(BeautifulSoup) -> 價值數據html
Demo1:node
# coding:utf8 import urllib2,cookielib url = "https://www.baidu.com" print '第一種方法' response1 = urllib2.urlopen(url) print response1.getcode() #返回狀態碼 print len(response1.read()) #返回的網頁內容的長度 print "第二種方法" request = urllib2.Request(url) request.add_header("user-agent","Mozilla/5.0") response2 = urllib2.urlopen(request) print response2.getcode() print len(response2.read()) print '第三種方法' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) response3 = urllib2.urlopen(url) print response3.getcode() #返回狀態碼 print cj #返回cookie print response3.read() #返回網頁內容
Python有哪幾種網頁解析器:
正則表達式、html.parser、Beautiful Soup、lxml
BeautifulSoup:
- Python第三方庫,用於從HTML或XML中提取數據
- 官網:http://www.crummy.com/software/BeautifulSoup/bs4/doc/python
安裝並測試beautifulsoup4:
- 安裝:pip install beautifulsoup4
- 測試:import bs4git
若是PyCharm沒法識別beautifulsoup4,則在設置裏找到Python Intercepter這一項,改成python2.7版本便可。
github
Demo2:正則表達式
# coding:utf-8 import re from bs4 import BeautifulSoup # 示例代碼片斷(來自beautifulsoup官網) html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc,'html.parser',from_encoding='utf-8') print '獲取全部的連接' links = soup.find_all('a') for link in links: print link.name,link['href'],link.get_text() print '獲取lacie的連接' link_node = soup.find('a',href='http://example.com/lacie') print link_node.name,link_node['href'],link_node.get_text() print '正則匹配' link_node = soup.find('a', href= re.compile(r"ill")) print link_node.name,link_node['href'],link_node.get_text() print '獲取p段落文字' p_node = soup.find('p', class_="title") print p_node.name,p_node.get_text()
實戰編寫爬取百度百科頁面:服務器
目錄結構:cookie
注:mac osx下用alt+enter添加相應方法多線程
(爬蟲調度器)spider_main.py:app
# coding=utf-8 from baike_spider import url_manager,html_downloader,html_parser,html_outputer class SpiderMain(object): def __init__(self): self.urls = url_manager.UrlManager() #url管理器 self.downloader = html_downloader.HtmlDownloader() #下載器 self.parser = html_parser.HtmlParser() #解析器 self.outputer = html_outputer.HtmlOutputer() #輸出器 def craw(self, root_url): count = 1 #判斷當前爬取的是第幾個url self.urls.add_new_url(root_url) while self.urls.has_new_url(): #循環,爬取全部相關頁面,判斷異常狀況 try: new_url = self.urls.get_new_url() #取得url print 'craw %d : %s' % (count, new_url) #打印當前是第幾個url html_cont = self.downloader.download(new_url) #下載頁面數據 new_urls, new_data = self.parser.parse(new_url,html_cont) #進行頁面解析獲得新的url以及數據 self.urls.add_new_urls(new_urls) #添加新的url self.outputer.collect_data(new_data) #收集數據 if count == 10: # 此處10能夠改成100甚至更多,表明循環次數 break count = count + 1 except: print 'craw failed' self.outputer.output_html() #利用outputer輸出收集好的數據 if __name__=="__main__": root_url = "http://baike.baidu.com/view/21087.htm" obj_spider = SpiderMain() # 建立 obj_spider.craw(root_url) # craw方法啓動爬蟲
(url管理器)url_manager.py:
# coding=utf-8 class UrlManager(object): def __init__(self): self.new_urls = set() # 待爬取url self.old_urls = set() # 已爬取url def add_new_url(self, url): # 向管理器中添加一個新的url if url is None: return if url not in self.new_urls and url not in self.old_urls: self.new_urls.add(url) def add_new_urls(self, urls): # 向管理器中添加新的更多的url if urls is None or len(urls) == 0: return for url in urls: self.add_new_url(url) def has_new_url(self): # 判斷管理器是否有新的待爬取的url return len(self.new_urls) != 0 def get_new_url(self): # 從管理器中獲取一個新的待爬取的url new_url = self.new_urls.pop() self.old_urls.add(new_url) return new_url
(下載器)html_downloader.py:
import urllib2 class HtmlDownloader(object): def download(self, url): if url is None: return None response = urllib2.urlopen(url) if response.getcode() != 200: return None return response.read()
(解析器)html_parser.py:
import re import urlparse from bs4 import BeautifulSoup class HtmlParser(object): def parse(self,page_url,html_cont): if page_url is None or html_cont is None: return soup = BeautifulSoup(html_cont,'html.parser', from_encoding='utf-8') new_urls = self._get_new_urls(page_url, soup) new_data = self._get_new_data(page_url, soup) return new_urls, new_data def _get_new_urls(self, page_url, soup): new_urls = set() # /view/123.htm links = soup.find_all('a', href=re.compile(r"/view/\d+\.htm")) for link in links: new_url = link['href'] new_full_url = urlparse.urljoin(page_url, new_url) new_urls.add(new_full_url) return new_urls def _get_new_data(self, page_url, soup): res_data = {} # url res_data['url'] = page_url # <dd class="lemmaWgt-lemmaTitle-title"> <h1>Python</h1> title_node = soup.find('dd',class_="lemmaWgt-lemmaTitle-title").find("h1") res_data['title'] = title_node.get_text() # <div class="lemma-summary" label-module="lemmaSummary"> summary_node = soup.find('div',class_="lemma-summary") res_data['summary'] = summary_node.get_text() return res_data
(數據輸出)html_outputer.py:
# coding=utf-8 class HtmlOutputer(object): #初始化 def __init__(self): self.datas = [] def collect_data(self, data): #收集數據 if data is None: return self.datas.append(data) def output_html(self): #輸出數據 fout = open('output.html', 'w') fout.write("<html>") fout.write("<head>") fout.write("<meta charset= 'UTF-8'>") fout.write("</head>") fout.write("<body>") fout.write("<table>") # ASCII for data in self.datas: fout.write("<tr>") fout.write("<td>%s</td>" % data['url']) fout.write("<td>%s</td>" % data['title'].encode('utf-8')) fout.write("<td>%s</td>" % data['summary'].encode('utf-8')) fout.write("</tr>") fout.write("</html>") fout.write("</body>") fout.write("</table>") fout.close()
運行程序spider_main.py可進行爬取頁面,最終文件輸出爲output.html,裏面包含詞條和詞條解釋,爬取完畢。
output.html:
這只是最簡單的爬蟲,若是想深刻學習,還有登陸、驗證碼、Ajax、服務器防爬蟲、多線程、分佈式等等。