Python爬蟲實例

前言

Python很是適合用來開發網頁爬蟲,理由以下:
一、抓取網頁自己的接口
相比與其餘靜態編程語言,如java,c#,c++,python抓取網頁文檔的接口更簡潔;相比其餘動態腳本語言,如perl,shell,python的urllib2包提供了較爲完整的訪問網頁文檔的API。(固然ruby也是很好的選擇)
此外,抓取網頁有時候須要模擬瀏覽器的行爲,不少網站對於生硬的爬蟲抓取都是封殺的。這是咱們須要模擬user agent的行爲構造合適的請求,譬如模擬用戶登錄、模擬session/cookie的存儲和設置。在python裏都有很是優秀的第三方包幫你搞定,如Requests,mechanizehtml

二、網頁抓取後的處理
抓取的網頁一般須要處理,好比過濾html標籤,提取文本等。python的beautifulsoap提供了簡潔的文檔處理功能,能用極短的代碼完成大部分文檔的處理。
其實以上功能不少語言和工具都能作,可是用python可以幹得最快,最乾淨。java

Life is short, you need python.node

PS:python2.x和python3.x有很大不一樣.python

爬蟲架構

架構組成

URL管理器:管理待爬取的url集合和已爬取的url集合,傳送待爬取的url給網頁下載器。
網頁下載器(urllib):爬取url對應的網頁,存儲成字符串,傳送給網頁解析器。
網頁解析器(BeautifulSoup):解析出有價值的數據,存儲下來,同時補充url到URL管理器。mysql

運行流程

image

URL管理器

基本功能

  • 添加新的url到待爬取url集合中。
  • 判斷待添加的url是否在容器中(包括待爬取url集合和已爬取url集合)。
  • 獲取待爬取的url。
  • 判斷是否有待爬取的url。
  • 將爬取完成的url從待爬取url集合移動到已爬取url集合。

存儲方式

一、內存(python內存)
待爬取url集合:set()
已爬取url集合:set()c++

二、關係數據庫(mysql)
urls(url, is_crawled)正則表達式

三、緩存(redis)
待爬取url集合:set
已爬取url集合:setredis

大型互聯網公司,因爲緩存數據庫的高性能,通常把url存儲在緩存數據庫中。小型公司,通常把url存儲在內存中,若是想要永久存儲,則存儲到關係數據庫中。sql

網頁下載器(urllib)

將url對應的網頁下載到本地,存儲成一個文件或字符串。shell

基本方法

新建baidu.py,內容以下:

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')

buff = response.read()

html = buff.decode("utf8")

print(html)

命令行中執行python baidu.py,則能夠打印出獲取到的頁面。

構造Request

上面的代碼,能夠修改成:

import urllib.request

request = urllib.request.Request('http://www.baidu.com')

response = urllib.request.urlopen(request)

buff = response.read()

html = buff.decode("utf8")

print(html)

攜帶參數

新建baidu2.py,內容以下:

import urllib.request

import urllib.parse

url = 'http://www.baidu.com'

values = {'name': 'voidking','language': 'Python'}

data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore')

headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0' }

request = urllib.request.Request(url=url, data=data,headers=headers,method='GET')

response = urllib.request.urlopen(request)

buff = response.read()

html = buff.decode("utf8")

print(html)

使用Fiddler監聽數據

咱們想要查看一下,咱們的請求是否真的攜帶了參數,因此須要使用fiddler。
打開fiddler以後,卻意外發現,上面的代碼會報錯504,不管是baidu.py仍是baidu2.py。

雖然python有報錯,可是在fiddler中,咱們能夠看到請求信息,確實攜帶了參數。

通過查找資料,發現python之前版本的Request都不支持代理環境下訪問https。可是,最近的版本應該支持了纔對。那麼,最簡單的辦法,就是換一個使用http協議的url來爬取,好比,換成http://www.csdn.net。結果,依然報錯,只不過變成了400錯誤。

然而,然而,然而。。。神轉折出現了!!!
當我把url換成http://www.csdn.net/後,請求成功!沒錯,就是在網址後面多加了一個斜槓/。同理,把http://www.baidu.com改爲http://www.baidu.com/,請求也成功了!神奇!!!

添加處理器

import urllib.request

import http.cookiejar

# 建立cookie容器

cj = http.cookiejar.CookieJar()

# 建立opener

opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))

# 給urllib.request安裝opener

urllib.request.install_opener(opener)

# 請求

request = urllib.request.Request('http://www.baidu.com/')

response = urllib.request.urlopen(request)

buff = response.read()

html = buff.decode("utf8")

print(html)

print(cj)

網頁解析器(BeautifulSoup)

從網頁中提取出有價值的數據和新的url列表。

解析器選擇

爲了實現解析器,能夠選擇使用正則表達式、html.parser、BeautifulSoup、lxml等,這裏咱們選擇BeautifulSoup。
其中,正則表達式基於模糊匹配,而另外三種則是基於DOM結構化解析。

BeautifulSoup

安裝測試

一、安裝,在命令行下執行pip install beautifulsoup4
二、測試

import bs4

print(bs4)
使用說明


基本用法

一、建立BeautifulSoup對象

import bs4

from bs4 import BeautifulSoup

# 根據html網頁字符串建立BeautifulSoup對象

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)

print(soup.prettify())

二、訪問節點

print(soup.title)

print(soup.title.name)

print(soup.title.string)

print(soup.title.parent.name)

print(soup.p)

print(soup.p['class'])

三、指定tag、class或id

print(soup.find_all('a'))

print(soup.find('a'))

print(soup.find(class_='title'))

print(soup.find(id="link3"))

print(soup.find('p',class_='title'))

四、從文檔中找到全部<a>標籤的連接

for link in soup.find_all('a'):

        print(link.get('href'))


出現了警告,根據提示,咱們在建立BeautifulSoup對象時,指定解析器便可。

soup = BeautifulSoup(html_doc,'html.parser')

五、從文檔中獲取全部文字內容

print(soup.get_text())

六、正則匹配

link_node = soup.find('a',href=re.compile(r"til"))

print(link_node)

實例

# -*- coding: utf-8 -*-
'''
Created on 2017年4月10日

@author: xuxianglin
'''
import urllib2, os.path, urllib, random
from bs4 import BeautifulSoup
 
def get_soup(url):
    """
    獲取網站的soup對象
    """
    my_headers = [
    'Mozilla/5.0 (Windows NT 5.2) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30',
    'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0',
    'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET4.0E; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)',
    'Opera/9.80 (Windows NT 5.1; U; zh-cn) Presto/2.9.168 Version/11.50',
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1',
    'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET4.0E; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C)']
    header={"User-Agent":random.choice(my_headers)}
    req=urllib2.Request(url, headers=header)
    html=urllib2.urlopen(req).read()
    soup=BeautifulSoup(html)
    return soup
     
def get_pages(url):
    """
    獲取妹子圖網站的頁數
    """
    soup=get_soup(url)
    nums=soup.find_all('a',class_='page-numbers')
    pages=int(nums[-2].text)
    return pages
 
     
def get_menu(url):
    """
    獲取頁面的全部妹子圖主題的連接名稱和地址,記入列表
    """
    soup=get_soup(url)
    menu=[]
    menu_list=soup.find_all('a',target='_blank')
    for i in menu_list:
        result=i.find_all('img',class_='lazy')
        if result:
            name=result[0]['alt']
            address=i['href']
            menu.append([name,address])
    return menu
 
def get_links(url):
    """
    獲取單個妹子圖主題一共具備多少張圖片
    """
    soup=get_soup(url)
    all_=soup.find_all('a')
    nums=[]
    for i in all_:
        span=i.find_all('span')
        if span:
            nums.append(span[0].text)
    return nums[-2]
             
def get_image(url,filename):
    """
    從單獨的頁面中提取出圖片保存爲filename
    """
    soup=get_soup(url)
    image=soup.find_all('p')[0].find_all('img')[0]['src']
    urllib.urlretrieve(image,filename)
 
def main(page):
    """
    下載第page頁的妹子圖
    """
    print u'正在下載第 %d 頁' % page
    page_url=url+'/page/'+str(page)
    menu=get_menu(page_url)
    print u'@@@@@@@@@@@@@@@@第 %d 頁共有 %d 個主題@@@@@@@@@@@@@@@@' %(page,len(menu))
    for i in menu:
        dir_name=os.path.join('MeiZiTu',i[0])
        if not os.path.exists(dir_name):
            os.mkdir(dir_name)
        pic_nums=int(get_links(i[1]))
        print u'\n\n\n*******主題 %s 一共有 %d 張圖片******\n' %(i[0],pic_nums)
        for pic in range(1,pic_nums+1):
            basename=str(pic)+'.jpg'
            filename=os.path.join(dir_name,basename)
            pic_url=i[1]+'/'+str(pic)
            if not os.path.exists(filename):
                print u'......%s' % basename,
                get_image(pic_url,filename)
            else:
                print filename+u'已存在,略過'
     
if __name__=='__main__':
    url='http://www.mzitu.com/'
    pages=get_pages(url)
    print u'***************妹子圖一共有 %d 頁******************' %pages
    if not os.path.exists('MeiZiTu'):
        os.mkdir('MeiZiTu')
    page_start=input(u'Input the first page number:\n')
    page_end=input(u'Input the last page number:\n')
    if page_end>page_start:
        for page in range(page_start,page_end):
            main(page)
    elif page_end==page_start:
        main(page_end)
    else:
        print u"輸入錯誤,起始頁必須小於等於結束頁\n"
相關文章
相關標籤/搜索