Python爬蟲知識點一

LHBlog發表於2017-11-15

一。入門知識:

1.1.HTTP簡介
HTTP = HyperText Transfer Protocol
URI = Uniform Resource Identifier
URL = Uniform Resource Locator
URI和URL的區別:URI強調的是資源,而URL強調的是資源的位置。
1.2常用請求型別
OPTIONS: 返回伺服器針對特定資源所支援的http請求方法。
HEAD: 向伺服器索要與get請求相一致的響應,只不過響應體將不會被返回。
GET: 向特定資源發出請求
PUT: 向指定資源位置上傳其最新內容
POST: 向指定資源提交資料進行處理請求
DELETE: 請求伺服器刪除指定URI所標識的資源
PATCH: 用來將區域性修改應用於某一資源
1.3HTTP常見狀態碼
200/OK: 請求成功
201/Created: 請求已被實現,且一個新資源已根據請求被建立,URI跟隨Location頭資訊返回。
202/Accepted: 伺服器已接受請求,但尚未處理。
400/Bad Request: 請求無法被伺服器理解
401/Unauthorized: 當前請求需要使用者驗證
403/Forbidden: 伺服器已理解請求,但拒絕執行。
404/Not Found

1.4 爬蟲框架介紹
第一步:將種子URL放入佇列
第二步:從佇列中獲取URL,抓取內容。
第三步:解析抓取內容,將需要進一步抓取的URL放入工作佇列,儲存解析後的內容
1.5 抓取策略
深度優先:舉例先完成專題一的所有內容,再完成專題二的所有內容。

廣度優先
PageRank
大站優先策略 舉例:
根據網站的Pr順序 指定優先順序

1.6 如何去重
Hash表
bloom過濾器

1.7 爬蟲質量標準

分散式
可伸縮性
效能和有效性
質量
新鮮性
更新
可擴充套件性

二。程式碼實施

import requests
import xml.etree.ElementTree as ET
from xml.parsers.expat import ParserCreate


class DefaultSaxHandler(object):
    def __init__(self, provinces):
        self.provinces = provinces

    # 處理標籤開始
    def start_element(self, name, attrs):
        if name != 'map':
            name = attrs['title']
            number = attrs['href']
            self.provinces.append((name, number))

    # 處理標籤結束
    def end_element(self, name):
        pass

    # 文字處理
    def char_data(self, text):
        pass


def get_province_entry(url):
    # 獲取文字,並用gb2312解碼
    content = requests.get(url).content.decode('gb2312')
    # 確定要查詢字串的開始結束位置,並用切片獲取內容。
    start = content.find('<map name=\"map_86\" id=\"map_86\">')
    end = content.find('</map>')
    content = content[start:end + len('</map>')].strip()
    print(content)
    provinces = []
    # 生成Sax處理器
    handler = DefaultSaxHandler(provinces)
    # 初始化分析器
    parser = ParserCreate()
    parser.StartElementHandler = handler.start_element
    parser.EndElementHandler = handler.end_element
    parser.CharacterDataHandler = handler.char_data
    # 解析資料
    parser.Parse(content)
    # 結果字典為每一頁的入口程式碼
    return provinces


provinces = get_province_entry('http://www.ip138.com/post')
print(provinces)

結果如下:

Ps: start方法中判斷不等於map標籤的即為area標籤 然後選取href title屬性對應的值即可

 持續更新中。。。。,歡迎大家關注我的公眾號LHWorld.

相關文章