Python进阶(二十)Python爬虫实例讲解
生活随笔
收集整理的這篇文章主要介紹了
Python进阶(二十)Python爬虫实例讲解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、前言
- 二、爬蟲簡單架構
- 三、程序入口函數(爬蟲調度段)
- 四、URL管理器
- 五、網頁下載器
- 六、網頁解析器
- 七、網頁輸出器
- 八、運行結果
- 九、拓展閱讀
一、前言
本篇博文主要講解Python爬蟲實例,重點包括爬蟲技術架構,組成爬蟲的關鍵模塊:URL管理器、HTML下載器和HTML解析器。
二、爬蟲簡單架構
三、程序入口函數(爬蟲調度段)
#coding:utf8 import time, datetimefrom maya_Spider import url_manager, html_downloader, html_parser, html_outputerclass Spider_Main(object):#初始化操作def __init__(self):#設置url管理器self.urls = url_manager.UrlManager()#設置HTML下載器self.downloader = html_downloader.HtmlDownloader()#設置HTML解析器self.parser = html_parser.HtmlParser()#設置HTML輸出器self.outputer = html_outputer.HtmlOutputer()#爬蟲調度程序def craw(self, root_url):count = 1self.urls.add_new_url(root_url)while self.urls.has_new_url():try:new_url = self.urls.get_new_url()print('craw %d : %s' % (count, new_url))html_content = self.downloader.download(new_url)new_urls, new_data = self.parser.parse(new_url, html_content)self.urls.add_new_urls(new_urls)self.outputer.collect_data(new_data)if count == 10:breakcount = count + 1except:print('craw failed')self.outputer.output_html()if __name__ == '__main__':#設置爬蟲入口root_url = 'http://baike.baidu.com/view/21087.htm'#開始時間print('開始計時..............')start_time = datetime.datetime.now()obj_spider = Spider_Main()obj_spider.craw(root_url)#結束時間end_time = datetime.datetime.now()print('總用時:%ds'% (end_time - start_time).seconds)四、URL管理器
class UrlManager(object):def __init__(self):self.new_urls = set()self.old_urls = set()def add_new_url(self, url):if url is None:returnif url not in self.new_urls and url not in self.old_urls:self.new_urls.add(url)def add_new_urls(self, urls):if urls is None or len(urls) == 0:returnfor url in urls:self.add_new_url(url)def has_new_url(self):return len(self.new_urls) != 0def get_new_url(self):new_url = self.new_urls.pop()self.old_urls.add(new_url)return new_url五、網頁下載器
import urllib import urllib.requestclass HtmlDownloader(object):def download(self, url):if url is None:return None#偽裝成瀏覽器訪問,直接訪問的話csdn會拒絕user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = {'User-Agent':user_agent}#構造請求req = urllib.request.Request(url,headers=headers)#訪問頁面response = urllib.request.urlopen(req)#python3中urllib.read返回的是bytes對象,不是string,得把它轉換成string對象,用bytes.decode方法return response.read().decode()六、網頁解析器
import re import urllib from urllib.parse import urlparsefrom bs4 import BeautifulSoupclass HtmlParser(object):def _get_new_urls(self, page_url, soup):new_urls = set()#/view/123.htmlinks = soup.find_all('a', href=re.compile(r'/item/.*?'))for link in links:new_url = link['href']new_full_url = urllib.parse.urljoin(page_url, new_url)new_urls.add(new_full_url)return new_urls#獲取標題、摘要def _get_new_data(self, page_url, soup):#新建字典res_data = {}#urlres_data['url'] = page_url#<dd class="lemmaWgt-lemmaTitle-title"><h1>Python</h1>獲得標題標簽title_node = soup.find('dd', class_="lemmaWgt-lemmaTitle-title").find('h1')print(str(title_node.get_text()))res_data['title'] = str(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_datadef parse(self, page_url, html_content):if page_url is None or html_content is None:return Nonesoup = BeautifulSoup(html_content, '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:returnself.datas.append(data )def output_html(self):fout = open('maya.html', 'w', encoding='utf-8')fout.write("<head><meta http-equiv='content-type' content='text/html;charset=utf-8'></head>")fout.write('<html>')fout.write('<body>')fout.write('<table border="1">')# <th width="5%">Url</th>fout.write('''<tr style="color:red" width="90%"><th>Theme</th><th width="80%">Content</th></tr>''')for data in self.datas:fout.write('<tr>\n')# fout.write('\t<td>%s</td>' % data['url'])fout.write('\t<td align="center"><a href=\'%s\'>%s</td>' % (data['url'], data['title']))fout.write('\t<td>%s</td>\n' % data['summary'])fout.write('</tr>\n')fout.write('</table>')fout.write('</body>')fout.write('</html>')fout.close()八、運行結果
九、拓展閱讀
- 完整代碼
總結
以上是生活随笔為你收集整理的Python进阶(二十)Python爬虫实例讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 菜鸟要做架构师——java性能优化之fo
- 下一篇: html复选框值改变后事件,javasc