pwd #獲取當前所在路徑
'C:\\Users\\ZL'
cd D:\\python文件 ##更改當前路徑爲指定的路徑D:\python文件
D:\python文件
pwd #查看更改後的當前路徑
'D:\\python文件'
#獲取百度首頁內容 import urllib.request url = 'http://www.baidu.com' file = urllib.request.urlopen(url).read() #打開該網站,並讀取網站內容存儲在變量‘file’中 print(file) #打印出獲取的網站的內容
##將該網址內容給存於本地文件 fhandle = open("D:/python文件/1.html",'wb') #以寫入的方式打開一個本地文件,命名爲*.html等網頁格式 fhandle.write(file) #將爬取網頁的內容賦值給了上述中的變量‘file’,在這裏將變量的值寫入到該文件中(能夠看到寫入的字節數是112159) fhandle.close #關閉文件 ##這樣咱們就將剛剛成功獲取到的百度首頁的內容保存到了本地(D:\python文件)文件夾下,可在該文件夾下查看
112159
##也能夠經過urllib.request.urlretrieve()將獲取的內容保存到本地文件中 filename = urllib.request.urlretrieve('http://edu.51cto.com',filename = "D:/python文件/2.html")
urllib.request.urlcleanup()
urllib.request.urlopen(url).getcode()
200
urllib.request.urlopen(url).geturl()
'http://www.baidu.com'
urllib.request.quote('https://www.sina.com.cn')
'https%3A//www.sina.com.cn'
urllib.request.unquote("https%3A//www.sina.com.cn")
'https://www.sina.com.cn'
對於沒法爬取的網頁,可以使用下面的代碼(先任意打開一個網頁,進入首頁後按F12,隨便百度一個連接html
###兩種方法,其區別之處就在於尾端的s和有沒有下劃線 import urllib.request url = ("輸入要爬取的網址")#定義了要爬取的網址賦給變量url headers = ("User-Agent","從瀏覽器中獲取的具體信息")#格式爲(「User-Agent」,具體信息) opener = urllib.request.build_opener()#修改報頭 opener.addheaders = [headers] data = opener.open(url).read 或 import urllib.request url = ("輸入要爬取的網址") req = urllib.Request(url)#建立一個Request對象賦給req req.add_header('User-Agent','從瀏覽器中獲取的具體信息') data = urllib.request.urlopen(req).read()#打開了對應的網址,而且讀取了網頁內容,賦給了變量data
##網頁超時的時候,沒法打開網頁,咱們便可根據本身的須要而安排超時的時間值 import urllib.request for i in range(1,100): try: file = urllib.request.urlopen("此處是須要爬取的網址",timeout=1)##超時設置爲1秒鐘,也就是說1秒鐘未響應的話就斷定爲超時,並讀取該網站的內容,輸出獲取到的內容的長度 data = file.read() print(len(data)) except Exception as e: print("出現異常-->"+str(e))##若是超時,則會引起異常,輸出「出現異常」等字樣,並輸出對應的異常緣由 ##若是要在爬取的時候設置超時異常的值,能夠在urlopen()打開網址的時候經過timeout字段設置,格式爲urllib.request.urlopen(要打開的網址,timeout=時間值)
import urllib.request for i in range(1,10): try: file = urllib.request.urlopen("http://yum.iqianyue.com",timeout=20)#響應時間爲20,即在20秒以內向該網站發送了大量的請求,繼而在短期內沒法響應 data = file.read() print(len(data)) except Exception as e: print("出現異常-->"+str(e))
14165 14165 14165 14165 14165 14165 14165 14165 14165
即在同一個IP去爬取同一個網站上的網頁,有時候就可能被屏蔽,則使用代理服務器,繼而顯示的不是咱們的IP 地址,而是代理服務器的IP地址
固然能夠從整理好的網址http://yum.iqianyue.com/proxy中找到許多代理服務器地址python
def use_proxy(proxy_addr,url): #自定義函數,實現使用代理服務器爬取網頁的功能(第一個形參爲代理服務器的地址,第二個爲爬取網頁的地址) import urllib.request proxy = urllib.request.ProxyHandler({"http":proxy_addr})#設置代理服務器信息 opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler)#建立對象opener,第一個爲代理信息,第二個爲類 urllib.request.install_opener(opener)#建立全局默認的opener對象 data = urllib.request.urlopen(url).read().decode('utf-8')#將獲取的網址內容進行編碼 return data proxy_addr="42.4.215.69:80" data = use_proxy(proxy_addr,"http://www.baidu.com") print(len(data)) #若某個IP地址打不開的話,估計就是失效了,多找幾個IP地址試試
8993
import urllib.request httphd = urllib.request.HTTPHandler(debuglevel=1) httpshd = urllib.request.HTTPSHandler(debuglevel=1) opener = urllib.request.build_opener(httphd,httpshd)#建立自定義對象 urllib.request.install_opener(opener)#建立全局默認的opener對象 data = urllib.request.urlopen("http://edu.51cto.com")
send: b'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: edu.51cto.com\r\nConnection: close\r\nUser-Agent: Python-urllib/3.5\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Date header: Content-Type header: Transfer-Encoding header: Connection header: Set-Cookie header: Server header: Vary header: Vary header: Vary header: Set-Cookie header: Expires header: Cache-Control header: Pragma header: Set-Cookie header: Set-Cookie header: Set-Cookie header: Load-Balancing header: Load-Balancing
用URL異常處理器——URLErro類進行相應的處理,須要導入urllib.error模塊(HTTPErro是URLErro的子類)瀏覽器
import urllib.request import urllib.error try: urllib.request.urlopen("http://blog.csdn.net")#對該網頁進行爬取 except urllib.error.HTTPError as e:##先用子類處理異常 print(e.code) print(e.reason) except urllib.error.URLError as e:#用父類處理異常 print(e.reason) ## 先用子類處理異常,處理不了的話再用父類處理異常
send: b'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: blog.csdn.net\r\nConnection: close\r\nUser-Agent: Python-urllib/3.5\r\n\r\n' reply: 'HTTP/1.1 200 OK\r\n' header: Server header: Date header: Content-Type header: Content-Length header: Connection header: Vary header: Cache-Control