天天看點

python 網絡爬蟲入門筆記

參考:http://www.cnblogs.com/xin-xin/p/4297852.html

一、簡介

  爬蟲即網絡爬蟲,如果将網際網路比做成一張大網,那麼蜘蛛就是爬蟲。如果它遇到資源,将會抓取下來。

二、過程

  在我們浏覽網頁時,我們經常會看到一些形形色色的頁面,其實這個過程就是我們輸入url,經DNS解析成對應的ip找到對應的伺服器主機,向伺服器發出一個請求,伺服器經過解析之後将html,js等發回浏覽器顯示。

  其實爬蟲和這個過程差不多,隻不過我們在抓取到html後,通過正規表達式來确定要擷取的内容。

三、urllib庫的使用

  1.抓住頁面的html:

         

#!/usr/bin/python
# -*- coding: utf-8 -*-  
import urllib,urllib2
url = 'http://www.baidu.com'
response = urllib2.urlopen(url)
html = response.read()
print html

          

  2.構造request

  比如,将上面代碼可以這樣改寫:

#!/usr/bin/python
# -*- coding: utf-8 -*-  
import urllib,urllib2
url = 'http://www.baidu.com'
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read()
print html

          

  3.GET和POST資料的傳輸

  POST:

  注:隻是示範方法   由于網站還有header  cookie 等驗證 代碼并不能登陸

#!/usr/bin/python
# -*- coding: utf-8 -*-  
import urllib,urllib2
values = {"username":"xxxxxx","password":"xxxxxx"}
data = urllib.urlencode(values)
url = "http://www.xiyounet.org/checkout/"
request = urllib2.Request(url,data)
reponse = urllib2.urlopen(request)
print reponse.read()
          

  GET:

#!/usr/bin/python
# -*- coding: utf-8 -*-  
import urllib,urllib2
values = {"username":"xxxxxx","password":"xxxxxx"}
data = urllib.urlencode(values)
url = "http://www.xiyounet.org/checkout/"
geturl = url + "?" +data
request = urllib2.Request(geturl)
reponse = urllib2.urlopen(request)
print reponse.read()
          

  4.設定headers

  由于大多數網站并不能像上面一樣登陸,為了能夠更全面的模拟浏覽器,是以我們有必要來學習header

#!/usr/bin/python
# -*- coding: utf-8 -*-  
import urllib,urllib2
url = "http://www.xiyounet.org/checkout/"
user_agent =  "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36"
referer = "http://www.xiyounet.org/checkout/"
values = {"username":"xxxxx","password":"xxxxx"}
headers = {'User-Agent':user_agent,'Referer':referer}
data = urllib.urlencode(values)
request = urllib2.Request(url,data,headers)
reponse = urllib2.urlopen(request)
print reponse.read()
          

  5.cookie的使用

    ⑴cookie是指一些網站用于辨識使用者身份、進行session跟蹤而存儲在使用者本地終端上的資料(一般是被加密)。我們在爬蟲時,如果遇到有登陸的網站,若沒有登陸是不 允許抓取的,我們可以擷取到cookie後模拟登陸,進而達到抓取目的

  urllib2中兩個重要的概念:

  •  openers: 我們都知道 urlopen()這個函數,其實它就是urllib2函數的opener,其實我們也可以去建立自己喜歡的opener 
  • handler:
http://www.jb51.net/article/46495.htm      

      ⑵cookielib子產品:它的功能主要是提供可供存儲的cookie對象配合urllib2來通路internet  我們可以用該子產品的cookiejar類的對象來擷取cookie:

      它與urllib2子產品結合使用來模拟登陸,主要的方法有:CookieJar  , FileCookieJar ,  MozillaCookieJar  ,LWPcookieJar

#!usr/bin/python
#coding:utf-8
import urllib2
import cookielib
#聲明一個cookieJar對象執行個體來儲存cookie
cookie = cookielib.CookieJar()
#利用urllib2庫的HTTPCookieProcessor的對象來建立cookie處理器
handler = urllib2.HTTPCookieProcessor(cookie)
#通過handler來建構opener
opener = urllib2.build_opener(handler)
#後面也可以request通路
response = opener.open("http://www.xiyounet.org/checkout/")
for item in cookie:
    print 'Name = '+item.name
    print 'value = '+item.value      

    ⑶将cookie儲存至檔案

    

#!usr/bin/python
#coding:utf-8
import urllib2
import cookielib

filename = 'cookie.txt'
#聲明一個MozillaCookieJar對象執行個體來儲存cookie,并寫入檔案
cookie = cookielib.MozillaCookieJar(filename)
#利用urllib2庫的HTTPCookieProcessor的對象來建立cookie處理器
handler = urllib2.HTTPCookieProcessor(cookie)
#通過handler來建構opener
opener = urllib2.build_opener(handler)
#後面也可以request通路
response = opener.open("http://www.xiyounet.org/checkout/")
#save方法的兩個參數
#ignore_discard:儲存cookie
#ignore_expires:如果存在則覆寫
cookie.save(ignore_discard = True,ignore_expires = True)      

    ⑷從檔案中讀取:

    

#usr/bin/python
#coding:utf-8
import cookielib
import urllib2

#建立MozillaCookieJar執行個體對象
cookie = cookielib.MozillaCookieJar()
#從檔案中讀取cookie内容到變量
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
#建立請求的request
req = urllib2.Request("http://www.xiyounet.org/checkout/")
#利用urllib2的build_opener方法建立一個opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
response = opener.open(req)
print response.read()      

    ⑸實戰:登陸簽到系統

     

    可能是伺服器設定了什麼權限,這個傳回400

#usr/bin/python
#coding:utf-8
import cookielib
import urllib2
import urllib
url = "http://www.xiyounet.org/checkout/index.php"
passdata = urllib.urlencode({'Username':'songxl','Password':'Songxl123456'})
cookiedata = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0","Referer":"http://www.xiyounet.org/checkout/","Host":"http://www.xiyounet.org"}
#設定儲存cookie的檔案,同級目錄下的cookie.txt
filename = 'cookie.txt'
#聲明一個MozillaCookieJar對象執行個體來儲存cookie,之後寫入檔案
cookie = cookielib.MozillaCookieJar(filename)
#利用urllib2庫的HTTPCookieProcessor對象來建立cookie處理器
handler = urllib2.HTTPCookieProcessor(cookie)
#通過handler來建構opener
opener = urllib2.build_opener(handler)
req = urllib2.Request(url.encode('utf-8'),passdata,cookiedata)
result = opener.open(req)
print result.read()      

  

  

  

轉載于:https://www.cnblogs.com/songxl/p/5196801.html