Python模塊之requests,urllib和re

目錄

  1、爬蟲的步驟

  2、使用Jupyter

  3、爬蟲請求模塊之urllib

  4、爬蟲請求模塊之requests

  5、爬蟲分析之re模塊

1、爬蟲的步驟

  1.發起請求,模擬瀏覽器發送一個http請求html

  2.獲取響應的內容node

  3.解析內容(解析出對本身有用的部分)python

    a.正則表達式mysql

    b.BeautifulSoup模塊web

    c.pyquery模塊正則表達式

    d.selenium模塊redis

  4.保存數據sql

    a.文本文件(txt,csv等)chrome

    b.數據庫(mysql)數據庫

    c.redis,mongdb(最長使用)

2、使用Jupyter

  2.1.使用理由:Jupyter能夠一次執行,講結果保存到內存裏,供後面python語句屢次使用,避免每次調試程序,都要從新請求網頁,頻繁爬取某個網頁,容易致使該網站封IP

  2.2.使用步驟:

    a.安裝:pip install jupyter (前提是已經安裝了python3)

    b.運行:jupyter  notebook,瀏覽器自動彈出使用界面

    c.右側New-->python3,新建一個python程序

  2.3.快捷鍵

    shift + enter鍵  :選定行執行,執行結果保留到內存

3、爬蟲請求模塊之urllib

  3.1 urllib介紹

Python標準庫中提供了:urllib等模塊以供Http請求,可是它的API能力不佳,須要巨量的工做,甚至包括各類方法覆蓋,來完成最簡單的任務,不推薦使用,此處只是瞭解一下

  3.2 簡單使用

#方式一:
import urllib.request

f = urllib.request.urlopen('http://www.baidu.com')
result = f.read().decode('utf-8')
print(result)


#方式二:
import urllib.request
req = urllib.request.Request('http://www.baidu.com')
response = urllib.urlopen(req)
result = response.read().decode('utf-8')
print(result)

ps:硬要使用urllib模塊,推薦使用方式二,由於req是一個Request對象,在這個對象裏,能夠定義請求的頭部信息,這樣能夠把本身包裝成像個瀏覽器發起的請求,以下面的一個例子

  3.3自定義請求頭信息

import urllib.request
req = urllib.request.Request('http://www.example.com')

#自定義頭部,第一個參數爲關鍵字參數key,第二個參數爲內容
req.add_header("User-Agent","Mozilla/5.0(X11;Ubuntu;Linux x86_64;rv:39.0) Gecko/20100101 Firefox/39.0") 

f = urllib.request.urlopen(req)
result = f.read().decode('utf-8')

#有一個模塊fake_useragent能夠隨機產生User-Agent信息,對於網站的反爬蟲機制有必定的欺騙做用

  3.4 fake_useragent使用

#1.安裝pip install fake_useragent

#2.基本使用
from fake_useragent import UserAgent
ua = UserAgent()
print(ua.chrome)   #產生一個谷歌的內核字段

#經常使用屬性
ua.chrome      #產生一個谷歌的內核字段
ua.ie              #隨機產生ie內核字段
ua.firefox       #隨機產生火狐內核字段
ua.random    #隨機產生不一樣瀏覽器的內核字段

4、爬蟲請求模塊之requests

  4.1 requests模塊介紹

Requests是使用Apache2 Licensed許可證的,基於Python開發的HTTP庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得進行網絡請求時,
變得美好了許多,並且使用Requests能夠垂手可得的完成瀏覽器能夠作到的任何操做

  4.2 requests安裝

pip3 install requests

  4.3 簡單使用

import requests

r = requests.get('http://www.example.com')
print(type(r))
print (r.status_code)   #服務器返回的狀態碼
print (r.encoding)       #網站使用的編碼
print (r.text)              #返回的內容,字符串類型

  4.4 get請求

#1.無參數實例
import requests
res = requests.get('http://www.example.com')

print (res.url)    #打印請求的url
print (res.text)    #打印服務器返回的內容


#2.有參數實例
import requests
payload = {'k1':'v1','k2':'v2'}
res = requests.get('http://httpbin.org/get',params=payload)

print (res.url)
print (res.text)

#3.解析json
import requests
import json

response = rquests.get('http://httpbin.org/get')
print (type(response.text))    #返回結果是字符串類型
pirnt (response.json())          #字符串轉成json格式
print (json.loads(response.text))  #字符串轉成json格式
print (type(response.json()))    #json類型


#4.添加headers
import requests
from fake_useragent import UserAgent
ua = UserAgent()

#自定義請求頭部信息
headers= {
    'User-Agent':ua.chrome
}
response = requests.get('http://www.zhihui.com',headers = headers)
print (response.text)

   4.5 post請求

#1.基本POST實例

import requests

#當headers爲application/content的時候,請求實例以下:
payload = {'k1':'v1','k2':'v2'}
res = requests.post('http://httpbin.org/post',data = payload)

print (res.text)
print (type(res.headers),res.headers)
print (type(res.cookies),res.cookies)
print (type(res.url),res.url)
print (type(res.history),res.history)


#2.發送請求頭和數據實例
import json
import requests

url = 'http://httpbin.org/post'
payload = {'some':'data'}
headers = {'content-type':'application/json'}

#當headers爲application/json的時候,請求實例以下:
res = requests.post(url,data=json.dumps(payload), headers = headers)

print (res.text)

  4.6關於get與post請求的差異

get請求方法參數只有params,而沒有data參數,而post請求中二者都是有的

  4.7 http返回代碼

 1 100:continue
 2 101 : switching_protocols
 3 102 : processing
 4 103 : checkpoint
 5 122 : uri_too_long , request_uri_too_long
 6 
 7 200 : ok , okay, all_ok all_okay , all_good, \\o/ , ''
 8 201 : created
 9 202 : accepted
10 203 : non_authoritative_info , non_authoritative_information
11 204 : no_content
12 205 : rest_content , reset
13 206 : partial_content, partial
14 207 :multi_status , multiple_status multi_stati multiple_stati
15 208 : already_reported
16 226 : im_used
17 
18 #Redirection
19 300 :multipel_choices
20 301 : moved_permanently , moved , \\o-
21 302 : found
22 303 : see_other , other
23 304 : not_modified
24 305 : use_proxy
25 306 : switch_proxy
26 307 : remporay_redirect , temporary_moved , temporary
27 308 : permanent_redirect , resume_incomplete , resume  #These 2 to be removed in 3.0
28 
29 #client Error
30 400 :bad_request , bad
31 401 : unauthorized
32 402 : payment_required payment
33 403 : forbiden
34 404 : not_found , -o-
35 405 : method_not_allowed not_allowed
36 406 : not_acceptable
37 407 : proxy_authentication_required , proxy_auth , proxy_authentication
38 408 : request_timeout  , timeout
39 409 : conflict 
40 410 :gone
41 411 :length_required
42 412 : precondition_failed , precondition
43 413 : request_entity_too_large
44 414 : requests_uri_too_large
45 415 : unsupported_media_type, unsupported_media , media_type
46 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
47 417: ('expectation_failed',),
48 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
49 421: ('misdirected_request',),
50 422: ('unprocessable_entity', 'unprocessable'),
51 423: ('locked',),
52 424: ('failed_dependency', 'dependency'),
53 425: ('unordered_collection', 'unordered'),
54 426: ('upgrade_required', 'upgrade'),
55 428: ('precondition_required', 'precondition'),
56 429: ('too_many_requests', 'too_many'),
57 431: ('header_fields_too_large', 'fields_too_large'),
58 444: ('no_response', 'none'),
59 449: ('retry_with', 'retry'),
60 450: ('blocked_by_windows_parental_controls', 'parental_controls'),
61 451: ('unavailable_for_legal_reasons', 'legal_reasons'),
62 499: ('client_closed_request',),
63 # Server Error.
64 500: ('internal_server_error', 'server_error', '/o\\', ''),
65 501: ('not_implemented',),
66 502: ('bad_gateway',),
67 503: ('service_unavailable', 'unavailable'),
68 504: ('gateway_timeout',),
69 505: ('http_version_not_supported', 'http_version'),
70 506: ('variant_also_negotiates',),
71 507: ('insufficient_storage',),
72 509: ('bandwidth_limit_exceeded', 'bandwidth'),
73 510: ('not_extended',),
74 511: ('network_authentication_required', 'network_auth', 'network_authentication')
View Code

   4.8 得到cookies

#會話登陸
import requests

s = requests.Session()
s.get('http://www.httpbin.org/cookies/set/123456789') #設置cookies
res = s.get('http://www.httpbin.org/cookies')  #得到cookies
print (res.text)   #打印cookies

此httpbin.org是經過以上方式來設置cookies


#得到cookie
import requests
response = requests.get('http://www.baidu.com')
#print ('response.cookies')

for key,value in reponse.cookies.items():
    print (key + '=' + value)         #組合key = value

  4.7 SSL設置

#ssl設置
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
res = requests.get('http://www.12306.cn',verify = False)
print (res.status_code)


#證書認證
import requests
res = requests.get('https://www.12306.cn',cert=('/path/server.crt','/path/key'))
print (res.status_code)

  4.8 代理設置

import requests
proxies = {
    "http":"http://127.0.0.1:9746",
    "https":"https://127.0.0.1:9924"
}

res = requests.get("http://www.taobao.com",proxies = procies)
print (res.status_code)


#有密碼的代理
import requests
proxies = {
    "https":"https://user:password@127.0.0.1:9924"
}

res = requests.get("http://www.taobao.com",proxies = procies)
print (res.status_code)

  4.9 超時時間設置與異常處理

import requests
from requests.exceptions import ReadTimeout
try:
    res = requests.get('http://httpbin.org/get',timeout=0.5)
except ReadTimeout:
    print ('Timeout')

  4.10 案例:檢測QQ是否在線

import urllib
import requests
from xml.etree import ElementTree as ET

#使用內置模塊urllib發送http請求
r = urllib.request.urlopen('http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=3455306**')
result = r.read().decode('utf-8')


#使用第三方模塊requests發送http請求
r = requetsts.get('http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=3455306**')
result = r.text

#解析XML格式內容
node = ET.XML(result)

#獲取內容
if node.text =='Y':
    print ('在線')
else:
    print ('離線')

 

5、爬蟲分析之re模塊

  5.1 關於re模塊的使用方法

http://www.cnblogs.com/lisenlin/articles/8797892.html#1

  5.2 爬蟲簡單案例

import requests
import re
from fake_useragent import UserAgent

def get_page(url):
    ua = UserAgent()
    headers = {
        'User-Agent':ua.chrome,
    }
    response = requests.get(url, headers = headers)
    try:
        if response.status_code == 200:
            res = response.text
            return res
        return None
    except Exception as e:
        print(e)

def get_movie(html):
    partten = '<p.*?><a.*?>(.*?)</a></p>.*?<p.*?>(.*?)</p>.*?<p.*?>(.*?)</p>'
    items = re.findall(partten, html, re.S)
    #print((items))
    return items
    
def write_file(items):
    fileMovie = open('movie.txt', 'w', encoding='utf8')
    try:
        for movie in items:
            fileMovie.write('電影排名:' + movie[0] + '\r\n')
            fileMovie.write('電影主演:' + movie[1].strip() + '\r\n')
            fileMovie.write('上映時間:' + movie[2] + '\r\n\r\n')
        print('文件寫入成功...')
    finally:
        fileMovie.close()
        
def main(url):
    html = get_page(url)
    items = get_movie(html)
    write_file(items)
    
if __name__ == '__main__':
    url = "http://maoyan.com/board/4"
    main(url)
相關文章
相關標籤/搜索