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的header
request.add_header('User-Agent', 'Mozilla/5.0')
# 發送請求獲取結果
response = urllib2.urlopen(request)
3. 添加特殊情景的處理器:

import urllib2, cookielib # 創建cookie容器 cj = cookielib.CookieJar() # 創建1個opener opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # 給urllib2安裝opener urllib2.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, cookielib
url = "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 cj
print 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 BeautifulSoup
import re
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='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()
