Python簡單爬取景點資訊
阿新 • • 發佈:2019-01-06
前言
網路爬蟲是為了獲取網際網路上的海量資訊資料,在互聯大資料加持的背景下,對資料合理利用成為了推動網際網路發展的原動力。對個人而言,可以利用爬蟲工具來獲取自己想要的資料資訊。海量的網際網路資料如何篩選到自己想要的,並且有價值的呢,這裡借取python的網路爬蟲模組來實現景點資訊爬取,進而獲取收集相關景點的資訊。
背景知識
Python爬蟲主要由URL管理器、URL下載器、URL解析器、資料輸出部分構成。不同的爬取內容,爬取的這幾個模組也不相同,特別是URL管理器以及URL解析器,它們的設計要與爬取網站的結構相匹配。Python的beautifulsoup模組是比較常用的爬蟲模組,它的解析功能非常強大,配合urlib模組可以實現簡單的爬蟲架構,下面是簡單用urlib獲取百度首頁內容的樣例:
#! /usr/bin/env python # encoding: utf-8 import urllib.request import http.cookiejar url = "http://www.baidu.com" #簡單爬取百度首頁 print ('simple crider') response1 = urllib.request.urlopen(url) print (response1.getcode()) print (len(response1.read())) #自定義客戶端爬取百度首頁 print ('comple crider') request = urllib.request.Request(url) request.add_header("user-agent","Mozilla/5.0") response2 = urllib.request.urlopen(request) print (response2.getcode()) print (len(response2.read())) #帶cookie爬取百度首頁 print ('cookie crider') cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) response3 = urllib.request.urlopen(url) print (response3.getcode()) print (cj) print (response3.read())
Python爬取景點資訊:
資料來源來自百科詞條,URL解析器根據詞條簡介欄的景點級別欄位進行識別該詞條是否屬於景點相關的詞條,然後由資料輸出模組進行相關資料資訊的收集整理輸出。
#!/usr/bin/env python # encoding: utf-8 from urllib import request from bs4 import BeautifulSoup from urllib.parse import urljoin import ssl import re # url管理器 class UrlManager(object): def __init__(self): self.new_url = set() self.old_url = set() # 新增 url def add_new_url(self, url): if url is None: return if url not in self.new_url or url not in self.old_url: self.new_url.add(url) # 新增新的 url def add_new_urls(self, urls): if urls is None: return for url in urls: self.new_url.add(url) # 判斷是否存在新的 url def has_new_url(self): return len(self.new_url) != 0 # 獲取新的 url def get_new_url(self): new_url = self.new_url.pop() self.old_url.add(new_url) return new_url # url下載器 class HtmlDownloader(object): def download(self, url): if url is None: return None # 開啟新的 URL response = request.urlopen(url) # 判斷返回值 if response.getcode() != 200: return None # 返回內容 return response.read() # url 解析器 class UrlParser(object): def _get_new_urls(self, page_url, soup): new_urls = set() links = soup.find_all('a', href=re.compile(r'/item/*')) for link in links: new_url = link['href'] new_full_url = 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') #<div class="basic-info cmn-clearfix" label-module="lemmaSummary"> summary_node = soup.find('div', class_='basic-info cmn-clearfix') #<dt class="basicInfo-item name">景點級別</dt> scenic_nodes = soup.find_all('dt', class_=re.compile(r'basicInfo-item *')) for scenic_node in scenic_nodes: if '景點級別' in scenic_node.get_text(): print (scenic_node.get_text()) #res_data['url'] = page_url res_data['title'] = title_node.get_text() res_data['summary'] = summary_node.get_text() return res_data return None def parse(self, page_url, html_cont): # 判斷 URL 和 cont 是否為 None if page_url is None or html_cont is None: return None 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 # 結果輸出器 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('out_put.html', 'w', encoding='utf-8') fout.write('<head>') fout.write('<body>') fout.write('<table style="border-color:#33A0E8;" border="1px"; align="center">') # Python 預設編碼格式是: Ascii for data in self.datas: fout.write('<tr>') fout.write('<td width="180px" height="auto" align="center">%s</td>' % data['title']) fout.write('<td width="80px" height="auto" align="center"> <a href=%s>景點詳情</a></td>' % data['url']) fout.write('<td>%s</td>' % data['summary']) fout.write('</tr>') fout.write('</table>') fout.write('</body>') fout.write('</head>') fout.close() class SpiderMain(object): def __init__(self): self.urls = UrlManager()#url_manager.UrlManager() self.downloader = HtmlDownloader()#html_downloader.HtmlDownloader() self.outputer = HtmlOutputer()#html_outputer.HtmlOutputer() self.parser = UrlParser()#html_parser.UrlParser() def craw(self, root_url): count = 1 # 新增 url self.urls.add_new_url(root_url) # 當 urls 存在 url 的時候進入迴圈,否則不進入 while self.urls.has_new_url(): try: # 獲取新的 url new_url = self.urls.get_new_url() print('craw %d : %s' % (count, new_url)) # 下載新的 url 的內容 html_cont = self.downloader.download(new_url) # 解析 url 和 資料 new_urls, new_data = self.parser.parse(new_url, html_cont) # 將新頁面的 url 新增到 url 中 self.urls.add_new_urls(new_urls) # 輸入器進行資料的收集 self.outputer.collect_data(new_data) # 資料條數可以自行設定,條目越多花費時間越長 if count == 2000: break count += 1 except: print('craw failed.') self.outputer.output_html() if __name__ == '__main__': # 程式入口的爬蟲 root_url = 'https://baike.baidu.com/item/%E7%99%BD%E4%BA%91%E5%B1%B1/1365' spider = SpiderMain() spider.craw(root_url)
抓取景點的部分資料
總結
爬蟲是非常常用的一種資料收集的手段,這裡簡單記錄使用python爬蟲的小樣例,並獲取百科詞條相關景點的資訊。非常感謝Simplation提供相關程式碼框架指引,記2019年初於廣州。