Python爬蟲02(urllib自帶模塊編寫)

Python 3.x版本後的urllib和urllib2

現在的Python已經出到了3.5.2

在Python 3以後的版本中,urllib2這個模塊已經不單獨存在(也就是說當你import urllib2時,系統提示你沒這個模塊),urllib2被合併到了urllib中,叫做urllib.request 和 urllib.error 。

urllib整個模塊分爲urllib.request, urllib.parse, urllib.error。

例: 
其中urllib2.urlopen()變成了urllib.request.urlopen() 
urllib2.Request()變成了urllib.request.Request()

一.urllib模塊的使用

1基本方法

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)

-----url:需要打開的網址

-----data:Post提交的數據

-----timeout:設置網站的訪問超時時間

直接用urllib.request模塊的urlopen()獲取頁面,數據格式爲bytes類型,需要decode()解碼,轉換成str類型。

import urllib.request

#向指定的url地址發送請求,並返回服務器響應的淚文件對象
response=urllib.request.urlopen(request)
#服務器返回的類文件對象支持python文件對象的操作方法
#read()方法就是讀取文件裏的全部內容,返回字符串
html=response.read()
html=html.decode('utf-8')

#返回http的響應碼
print(response.getcode())
#返回實際數據的實際url,防止重定向問題
print(response.geturl())
#返回服務器相應的http報頭
print(response.info())


#打印響應內容
print(html)

urlopen返回對象提供方法:

  • read(),readline(),readlines(),fileno(),close():對HTTPResponse類型數據進行操作
  • info():返回HTTPMessage對象,表示遠程服務器返回的是頭信息
  • getcode():返回http狀態碼,如果http請求,200請求成功完成;40wangzhiweizhaodao
  • geturl():返回請求的url

2.使用Request

urllib.request.Request(url,data=None,headers={},method=None)

使用request()來包裝請求,再通過urlopen()獲取頁面

import urllib.request

#爬蟲也反爬蟲第一步
#構建基礎的headers信息
ua_headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}
#通過urllib.request.Request()方法構造一個請求對象
request=urllib.request.Request("http://www.baidu.com/",headers=ua_headers)
#向指定的url地址發送請求,並返回服務器響應的淚文件對象
response=urllib.request.urlopen(request)
#服務器返回的類文件對象支持python文件對象的操作方法
#read()方法就是讀取文件裏的全部內容,返回字符串
html=response.read()

html=html.decode('utf-8')

#打印響應內容
print(html)

用來包裝頭部的數據:

- Usr-Agent:這個投不可以攜帶如下幾條信息:瀏覽器名和版本號,操作系統名和版本號,默認語言

-  Referer:可以用來放到連接,有一些網站圖片現實來源http://***.com,就是檢測Referer來鑑定的

- Connection:表示連接狀態,記錄Session的狀態

3.Post數據

urlopen()的data參數默認爲None,當data參數不爲空的時候,urlopen()提交方式爲Post

#usr/bin/python
#-*-coding:utf-8-*-
import urllib.request


from urllib import parse

ua_headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}

data={
    'first':'true',
    'pn':1,
    'kd':'Python'
}
data=parse.urlencode(data).encode('utf-8')
request=urllib.request.Request("http://www.lagou.com/jobs/positionAjax.json?",headers=ua_headers,data=data)


response=urllib.request.urlopen(request)

html=response.read()

html=html.decode('utf-8')

#打印響應內容
print(html)

urllib.parse.urlencode()主要作用是將url附上要提交的數據

經過urlencode()轉換後的data數據爲?first=true?pn=1?kd=Python,最後提交的url爲

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

4.Python 3中urlencode模塊的使用

urlencode方法所在位置 

urllib.parse.urlencode(values)

字符的編碼翻譯

from urllib import parse

wd={'wd':'歡迎你'}
print(parse.urlencode(wd))

輸出

使用

#usr/bin/python
#-*-coding:utf-8-*-
import urllib.request
from urllib import parse

url="http://www.baidu.com/s"
keyword=input("請輸入需要查詢的字符串:")
wd={"wd":keyword}
headers={"User-Agent": "Mozilla...."}
#通過parse.urlencode()參數是一個dict類型
wd=parse.urlencode(wd)
#拼接完整的url
fullurl=url+"?"+wd
#構建請求
request=urllib.request.Request(fullurl,headers=headers)
response=urllib.request.urlopen(request)

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

例子:簡單的貼吧爬取,並保存在本地

#usr/bin/python
#-*-coding:utf-8-*-
import urllib
from urllib import request,parse

def loadPage(url,filename):
    '''
    作用:根據url發送請求,獲取服務器響應羣文件
    url:需要爬取的url地址
    :return:
    '''
    print("正在下載"+filename)
    headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}
    request=urllib.request.Request(url,headers=headers)
    return urllib.request.urlopen(request).read()

def writePage(html,filename):
    '''
    作用:將html內容寫入到本地
    html:服務器相應文件內容
    :param html:
    :return:
    '''
    print("正在保存"+filename)
    #文件寫入操作   不需要做文件關閉操作,不需要做上下文操作
    with open(filename,"w") as f:
        f.write(str(html))
    print("保存完成")
    print("-"*30)
    
def tiebaSpider(url,beginPage,endPage):
    '''
    作用:貼吧爬蟲調度器,負責組合處理每個頁面的url
    url:貼吧的url前部分
    beginPage:起始頁
    endPage:結束頁
    :return:
    '''
    for page in range(beginPage,endPage+1):
        pn=(page-1)*50
        filename="第"+str(page)+"頁.html"
        fullurl=url+"&pn="+str(pn)
        # print (fullurl)
        html=loadPage(fullurl,filename)
        # print(html)
        writePage(html,filename)
    print("謝謝使用")
if __name__=="__main__":
    kw=input("請輸入需要爬取的貼吧名:")
    beginPage=int(input("請輸入起始頁:"))
    endPage=int(input("請輸入結束頁:"))

    url="http://tieba.baidu.com/f?"
    key=parse.urlencode({"kw":kw})
    fullurl=url+key
    tiebaSpider(fullurl,beginPage,endPage)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章