標籤:一段 實現 示範 object text att url tom alt
1. 目標:開發輕量級爬蟲(不包括需登陸的 和 Javascript非同步載入的)
不需要登陸的靜態網頁抓取
2. 內容:
2.1 爬蟲簡介
2.2 簡單爬蟲架構
2.3 URL管理器
2.4 網頁下載器(urllib2)
2.5 網頁解析器(BeautifulSoup)
2.6 完整執行個體:爬取百度百科Python詞條相關的1000個頁面資料
3. 爬蟲簡介:一段自動抓取互連網資訊的程式
爬蟲價值:互連網資料,為我所用。
4. 簡單爬蟲架構:
運行流程:
5. URL管理器:管理待抓取URL集合 和 已抓取URL集合
- 防止重複抓取、防止迴圈抓取
- 實現方式:
6. 網頁下載器:將互連網URL對應的網頁下載到本地的工具
- 分類:
- urllib2 下載網頁的方法:
1. 最簡潔方法: url ===> urllib2.urlopen(url)
import urllib2# 直接請求response = urllib2.urlopen(‘http://www.baidu.com‘)# 擷取狀態代碼,如果是200表示擷取成功print response.getcode()# 讀取內容cont = response.read()
2. 添加data、http header: (url,data,header) ===> urllib2.Request ===> urllib2.urlopen(request)
import urllib2# 建立Request對象request = urllib2.Request(url)# 添加資料request.add_data(‘a‘, ‘1‘)# 添加http的headerrequest.add_header(‘User-Agent‘, ‘Mozilla/5.0‘)# 發送請求擷取結果response = urllib2.urlopen(request)
3. 添加特殊情景的處理器:
import urllib2, cookielib# 建立cookie容器cj = cookielib.CookieJar()# 建立1個openeropener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))# 給urllib2安裝openerurllib2.install_opener(opener)# 使用帶有cookie的urllib2訪問網頁response = urllib2.urlopen(“http://www.baidu.com/”)
7. urllib2 執行個體代碼示範:
# -*- coding: utf-8 -*-"""Created on Tue Feb 14 10:31:06 2017@author: Wayne"""import urllib2, cookieliburl = "http://www.baidu.com"print "the 1st method"response1 = urllib2.urlopen(url)print response1.getcode()print len(response1.read())print "the 2nd method"request = urllib2.Request(url)request.add_header("user-agent", "Mozilla/5.0")response2 = urllib2.urlopen(request)print response2.getcode()print len(response2.read())print "the 3rd method"cj = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))response3 = urllib2.urlopen(url)print response3.getcode()print cjprint response3.read()
8. 網頁解析器:從網頁中提取有價值資料的工具
python 的網頁解析器:
結構化解析 - DOM ( Document Object Model) 樹:
9. 網頁解析器 - Beautiful Soup
9.1 Beautiful Soup
- Python 第三方庫,用於從HTML或XML中提取資料
- 官網:http://www.crummy.com/software/BeautifulSoup
9.2 安裝並測試 beautifulsoup4
- 安裝:pip install beautifulsoup4
- 測試:import bs4
9.3 Beautiful Soup文法
9.4 建立 BeautifulSoup 對象
from bs4 import BeautifulSoup# 根據 HTML 網頁字串建立 BeautifulSoup 對象soup = BeautifulSoup( html_doc, # HTML文檔字串 ‘html.parser‘ # HTML解析器 from_encoding=‘utf-8‘ # HTML文檔的編碼 )
9.5 搜尋節點(find_all, find)
# 方法:find_all(name, attrs, string)# 尋找所有標籤為 a 的節點soup.find_all(‘a‘)# 尋找所有標籤為 a,連結符合 /view/123.htm 形式的節點soup.find_all(‘a‘, href=‘/view/123.htm‘)soup.find_all(‘a‘, href=re.compiler(r‘/view/\d+\.htm‘))# 尋找所有標籤為div, class為abc,文字為Python的節點soup.find_all(‘div‘, class_=‘abc‘, string=‘Python‘)
9.6 訪問節點資訊
# 得到節點: <a href=‘1.html‘>Python</a># 擷取尋找到的節點的標籤名稱node.name# 擷取尋找到的a節點的href屬性node[‘href‘]# 擷取尋找到的a節點的連結文字node.get_text()
10. BeautifulSoup 執行個體測試
# -*- coding: utf-8 -*-"""Created on Tue Feb 14 11:00:42 2017@author: Wayne"""from bs4 import BeautifulSoupimport rehtml_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=‘urf-8‘)print ‘\n## Get all the links‘links = soup.find_all(‘a‘)for link in links: print link.name, link[‘href‘], link.get_text() print ‘\n## Get the links include "lacie"‘link_node = soup.find(‘a‘, href=‘http://example.com/lacie‘)print link_node.name, link_node[‘href‘], link_node.get_text()print ‘\n## RE matching‘link_node = soup.find(‘a‘, href=re.compile(r"ill"))print link_node.name, link_node[‘href‘], link_node.get_text()print ‘\n## Get "P" Paragraph Text‘p_node = soup.find(‘p‘, class_=‘title‘)print p_node.name, p_node.get_text()
Python 開發簡單爬蟲 - 基礎架構