urllib庫

爬蟲基礎php

1.爬蟲:請求網站並請求數據的自動化程序。html

2.爬蟲的基本流程:python

1.發起請求正則表達式

  經過http庫向目標站點發起請求,即發送一個request,請求包含額外的headers信息,等待服務器響應。數據庫

2.解析內容json

  獲得內容是HTML,能夠用正則表達式、網頁解析庫進行解析。多是json,多是二進制,能夠作進一步處理服務器

3.獲取響應內容cookie

  若是服務器正常響應會獲得一個response頁面內容,類型多是json字符串、二進制數據、HTML等。網絡

4.保存數據socket

  能夠保存爲文本,或者數據庫,特定格式。

2.urllib基本用法

官方文檔地址:https://docs.python.org/3/library/urllib.html

Urllibpython內置的HTTP請求庫
包括如下模塊
urllib.request 請求模塊
urllib.error 異常處理模塊
urllib.parse url解析模塊
urllib.robotparser robots.txt解析模塊

1.urlopen

關於urllib.request.urlopen參數的介紹:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

url參數的使用

urlopen通常經常使用的有三個參數,它的參數以下:
urllib.requeset.urlopen(url,data,timeout)
response.read()能夠獲取到網頁的內容,若是沒有read()

data參數的使用

這裏就用到urllib.parse,經過bytes(urllib.parse.urlencode())能夠將post數據進行轉換放到urllib.request.urlopendata參數中。這樣就完成了一次post請求。
因此若是咱們添加data參數的時候就是以post請求方式請求,若是沒有data參數就是get請求方式

import urllib.request

import urllib.parse

data=bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')

print(data)

response=urllib.request.urlopen('http://httpbin.org/post', data=data)

print(response.read())

timeout參數的使用
在某些網絡狀況很差或者服務器端異常的狀況會出現請求慢的狀況,或者請求異常,因此這個時候咱們須要給
請求設置一個超時時間,而不是讓程序一直在等待結果。例子以下:

import urllib.request

response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)

print(response.read())

  1. 異常處理

import urllib.request

import urllib.error

import socket

try:

    response=urllib.request.urlopen('http://httpbin.org/get', timeout=1)

except urllib.error.URLError as e:

    if isinstance(e.reason,socket.timeout):

        print(''TIME OUT'')

3.設置Headers
有不少網站爲了防止程序爬蟲爬網站形成網站癱瘓,會須要攜帶一些headers頭部信息才能訪問,最長見的有user-agent參數,使用urllib.request

#添加請求頭

from urllib import request,parse

url = 'http://httpbin.org/post'

headers = {

    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',

    'Host': 'httpbin.org'

}

dict = {

    'name': 'zhaofan'

}

data=bytes(parse.urlencode(dict),encoding='utf8')

req=request.Request(url=url,data=data,headers=headers,method='POST')

response=request.urlopen(req)

print(response.read().decode('utf-8'))

#第二種添加頭部信息方式

from urllib import request, parse

 

url = 'http://httpbin.org/post'

dict = {

    'name': 'Germey'

}

data = bytes(parse.urlencode(dict), encoding='utf8')

req = request.Request(url=url, data=data, method='POST')

req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')

response = request.urlopen(req)

4.高級用法各類handler

代理,ProxyHandler

經過rulllib.request.ProxyHandler()能夠設置代理,網站它會檢測某一段時間某個IP 的訪問次數,若是訪問次數過多,它會禁止你的訪問,因此這個時候須要經過設置代理來爬取數據

import urllib.request

 

proxy_handler = urllib.request.ProxyHandler({

    'http':'112.35.29.53:8088',

    'https':'165.227.169.12:80'

})

opener = urllib.request.build_opener(proxy_handler)

response = opener.open('http://www.baidu.com')

print(response.read())

5.cookie,HTTPCookiProcessor

cookie中保存中咱們常見的登陸信息,有時候爬取網站須要攜帶cookie信息訪問,這裏用到了http.cookijar,用於獲取cookie以及存儲cookie

import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)

 

同時cookie能夠寫入到文件中保存,有兩種方式http.cookiejar.MozillaCookieJarhttp.cookiejar.LWPCookieJar()

具體代碼例子以下:
http.cookiejar.MozillaCookieJar()方式

 

import http.cookiejar, urllib.request

filename = "cookie.txt"

cookie = http.cookiejar.MozillaCookieJar(filename)

handler = urllib.request.HTTPCookieProcessor(cookie)

opener = urllib.request.build_opener(handler)

response = opener.open('http://www.baidu.com')

cookie.save(ignore_discard=True, ignore_expires=True)

 

http.cookiejar.LWPCookieJar()方式

 

import http.cookiejar, urllib.request

filename = 'cookie.txt'

cookie = http.cookiejar.LWPCookieJar(filename)

handler = urllib.request.HTTPCookieProcessor(cookie)

opener = urllib.request.build_opener(handler)

response = opener.open('http://www.baidu.com')

cookie.save(ignore_discard=True, ignore_expires=True)

 

一樣的若是想要經過獲取文件中的cookie獲取的話能夠經過load方式,固然用哪一種方式寫入的,就用哪一種方式讀取。

 

import http.cookiejar, urllib.request

cookie = http.cookiejar.LWPCookieJar()

cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)

handler = urllib.request.HTTPCookieProcessor(cookie)

opener = urllib.request.build_opener(handler)

response = opener.open('http://www.baidu.com')print(response.read().decode('utf-8'))

 

異常處理

在不少時候咱們經過程序訪問頁面的時候,有的頁面可能會出現錯誤,相似404500等錯誤
這個時候就須要咱們捕捉異常,

from urllib import request,error

try:

    response = request.urlopen("http://pythonsite.com/1111.html")except error.URLError as e:

    print(e.reason)

上述代碼訪問的是一個不存在的頁面,經過捕捉異常,咱們能夠打印異常錯誤

這裏咱們須要知道的是在urllb異常這裏有兩個個異常錯誤:
URLError,HTTPErrorHTTPErrorURLError的子類

URLError裏只有一個屬性:reason,即抓異常的時候只能打印錯誤信息,相似上面的例子

HTTPError裏有三個屬性:code,reason,headers,即抓異常的時候能夠得到code,resonheaders三個信息,例子以下:

 

from urllib import request,errortry:

    response = request.urlopen("http://pythonsite.com/1111.html")except error.HTTPError as e:

    print(e.reason)

    print(e.code)

    print(e.headers)except error.URLError as e:

    print(e.reason)

else:

    print("reqeust successfully")

 

同時,e.reason其實也能夠在作深刻的判斷,例子以下:

 

import socket

from urllib import error,request

try:

    response = request.urlopen("http://www.pythonsite.com/",timeout=0.001)except error.URLError as e:

    print(type(e.reason))

    if isinstance(e.reason,socket.timeout):

        print("time out")

 

URL解析

urlparse
The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

功能一:

from urllib.parse import urlparse

 

result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")print(result)

結果爲:

 

這裏就是能夠對你傳入的url地址進行拆分
同時咱們是能夠指定協議類型:
result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
這樣拆分的時候協議類型部分就會是你指定的部分,固然若是你的url裏面已經帶了協議,你再經過scheme指定的協議就不會生效

urlunpars

其實功能和urlparse的功能相反,它是用於拼接,例子以下:

from urllib.parse import urlunparse

 

data = ['http','www.baidu.com','index.html','user','a=123','commit']print(urlunparse(data))

結果以下

 

urljoin

這個的功能實際上是作拼接的,例子以下:

 

from urllib.parse import urljoin

print(urljoin('http://www.baidu.com', 'FAQ.html'))print(urljoin('http://www.baidu.com', 'https://pythonsite.com/FAQ.html'))print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html'))print(urljoin('http://www.baidu.com/about.html', 'https://pythonsite.com/FAQ.html?question=2'))print(urljoin('http://www.baidu.com?wd=abc', 'https://pythonsite.com/index.php'))print(urljoin('http://www.baidu.com', '?category=2#comment'))print(urljoin('www.baidu.com', '?category=2#comment'))print(urljoin('www.baidu.com#comment', '?category=2'))

 

結果爲:

從拼接的結果咱們能夠看出,拼接的時候後面的優先級高於前面的url

urlencode
這個方法能夠將字典轉換爲url參數,例子以下

 

from urllib.parse import urlencode

 

params = {

    "name":"zhaofan",

    "age":23,

}

base_url = "http://www.baidu.com?"

 

url = base_url+urlencode(params)print(url)

 

結果爲:

相關文章
相關標籤/搜索