1.爬取百度首頁面所有數據值
#!/usr/bin/env python # -*- coding:utf-8 -*- #導包 import urllib.request import urllib.parse if __name__ == "__main__": #指定爬取的網頁url url = 'http://www.baidu.com/' #通過urlopen函數向指定的url發起請求,返回響應對象 reponse = urllib.request.urlopen(url=url) #通過調用響應對象中的read函數,返回響應回客戶端的數據值(爬取到的數據) data = reponse.read()#返回的數據為byte類型,並非字符串 print(data)#打印顯示爬取到的數據值。
補充說明:
urlopen函數原型:urllib.request.urlopen(url, data=None, timeout=<object object at 0x10af327d0>, *, cafile=None, capath=None, cadefault=False, context=None) 在上述案例中我們只使用了該函數中的第一個參數url。在日常開發中,我們能用的只有url和data這兩個參數。 url參數:指定向哪個url發起請求 data參數:可以將post請求中攜帶的參數封裝成字典的形式傳遞給該參數(暫時不需要理解,后期會講) urlopen函數返回的響應對象,相關函數調用介紹: response.headers():獲取響應頭信息 response.getcode():獲取響應狀態碼 response.geturl():獲取請求的url response.read():獲取響應中的數據值(字節類型)
2.將爬取到百度新聞首頁的數據值寫入文件進行存儲
#!/usr/bin/env python # -*- coding:utf-8 -*- import urllib.request import urllib.parse if __name__ == "__main__": url = 'http://news.baidu.com/' reponse = urllib.request.urlopen(url=url) #decode()作用是將響應中字節(byte)類型的數據值轉成字符串類型 data = reponse.read().decode() #使用IO操作將data表示的數據值以'w'權限的方式寫入到news.html文件中 with open('./news.html','w') as fp: fp.write(data) print('寫入文件完畢')
3.爬取網絡上某張圖片數據,且存儲到本地
#!/usr/bin/env python # -*- coding:utf-8 -*- import urllib.request import urllib.parse #如下兩行代碼表示忽略https證書,因為下面請求的url為https協議的請求,如果請求不是https則該兩行代碼可不用。 import ssl ssl._create_default_https_context = ssl._create_unverified_context if __name__ == "__main__": #url是https協議的 url = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1536918978042&di=172c5a4583ca1d17a1a49dba2914cfb9&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F0dd7912397dda144f04b5d9cb9b7d0a20cf48659.jpg' reponse = urllib.request.urlopen(url=url) data = reponse.read()#因為爬取的是圖片數據值(二進制數據),則無需使用decode進行類型轉換。 with open('./money.jpg','wb') as fp: fp.write(data) print('寫入文件完畢')
4.url的特性:url必須為ASCII編碼的數據值。所以我們在爬蟲代碼中編寫url時,如果url中存在非ASCII編碼的數據值,則必須對其進行ASCII編碼后,該url方可被使用。
案例:爬取使用百度根據指定詞條搜索到的頁面數據(例如爬取詞條為‘周傑倫’的頁面數據)
#!/usr/bin/env python # -*- coding:utf-8 -*- import urllib.request import urllib.parse if __name__ == "__main__": #原始url中存在非ASCII編碼的值,則該url無法被使用。 #url = 'http://www.baidu.com/s?ie=utf-8&kw=周傑倫' #處理url中存在的非ASCII數據值 url = 'http://www.baidu.com/s?' #將帶有非ASCII的數據封裝到字典中,url中非ASCII的數據往往都是'?'后面鍵值形式的請求參數 param = { 'ie':'utf-8', 'wd':'周傑倫' } #使用parse子模塊中的urlencode函數將封裝好的字典中存在的非ASCII的數值進行ASCII編碼 param = urllib.parse.urlencode(param) #將編碼后的數據和url進行整合拼接成一個完整可用的url url = url + param print(url) response = urllib.request.urlopen(url=url) data = response.read() with open('./周傑倫.html','wb') as fp: fp.write(data) print('寫入文件完畢')
5.通過自定義請求對象,用於偽裝爬蟲程序請求的身份。
之前在講解http常用請求頭信息時,我們講解過User-Agent參數,簡稱為UA,該參數的作用是用於表明本次請求載體的身份標識。如果我們通過瀏覽器發起的請求,則該請求的載體為當前瀏覽器,則UA參數的值表明的是當前瀏覽器的身份標識表示的一串數據。如果我們使用爬蟲程序發起的一個請求,則該請求的載體為爬蟲程序,那么該請求的UA為爬蟲程序的身份標識表示的一串數據。有些網站會通過辨別請求的UA來判別該請求的載體是否為爬蟲程序,如果為爬蟲程序,則不會給該請求返回響應,那么我們的爬蟲程序則也無法通過請求爬取到該網站中的數據值,這也是反爬蟲的一種初級技術手段。那么為了防止該問題的出現,則我們可以給爬蟲程序的UA進行偽裝,偽裝成某款瀏覽器的身份標識。
上述案例中,我們是通過request模塊中的urlopen發起的請求,該請求對象為urllib中內置的默認請求對象,我們無法對其進行UA進行更改操作。urllib還為我們提供了一種自定義請求對象的方式,我們可以通過自定義請求對象的方式,給該請求對象中的UA進行偽裝(更改)操作。
#!/usr/bin/env python # -*- coding:utf-8 -*- import urllib.request import urllib.parse import ssl ssl._create_default_https_context = ssl._create_unverified_context if __name__ == "__main__": #原始url中存在非ASCII編碼的值,則該url無法被使用。 #url = 'http://www.baidu.com/s?ie=utf-8&kw=周傑倫' #處理url中存在的非ASCII數據值 url = 'http://www.baidu.com/s?' #將帶有非ASCII的數據封裝到字典中,url中非ASCII的數據往往都是'?'后面鍵值形式的請求參數 param = { 'ie':'utf-8', 'wd':'周傑倫' } #使用parse子模塊中的urlencode函數將封裝好的字典中存在的非ASCII的數值進行ASCII編碼 param = urllib.parse.urlencode(param) #將編碼后的數據和url進行整合拼接成一個完整可用的url url = url + param #將瀏覽器的UA數據獲取,封裝到一個字典中。該UA值可以通過抓包工具或者瀏覽器自帶的開發者工具中獲取某請求,從中獲取UA的值 headers={ 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36' } #自定義一個請求對象 #參數:url為請求的url。headers為UA的值。data為post請求的請求參數(后面講) request = urllib.request.Request(url=url,headers=headers) #發送我們自定義的請求(該請求的UA已經進行了偽裝) response = urllib.request.urlopen(request) data=response.read() with open('./周傑倫.html','wb') as fp: fp.write(data) print('寫入數據完畢')
#爬蟲登錄開心網的賬號,並且爬取個人主頁內容
from urllib import request,parse
from http import cookiejar
import ssl
#取消SSL驗證
ssl._create_default_https_context=ssl._create_unverified_context
#定義請求管理器
#url.request.urlopen() 並不能保存cookie
http_handler=request.HTTPHandler()
https_handler=request.HTTPSHandler()
cookie=cookiejar.CookieJar()
#cookie管理器
cookie_handler=request.HTTPCookieProcessor(cookie)
##生成一個請求管理器
opener=request.build_opener(https_handler,http_handler,cookie_handler)
#登錄
def login(account,password):
#(1)
login_url='https://security.kaixin001.com/login/login_post.php'
data={
'email':account,
'password':password
}
data=parse.urlencode(data)
headers = {
"Content-Length": len(data),
"user_agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
}
req=request.Request(url=login_url,data=bytes(data,encoding='utf-8'),headers=headers)
# 2
response=opener.open(req)
html=response.read()
html=html.decode('utf-8')
# print(html)
# 在一個頁面html中查找特定子串 uid=
location = html.find('uid=')
print(location)
uid=html[location+4:location+4+9]
print(uid)
gerenpage(uid)
def gerenpage(uid):
# basu_url='http://www.kaixin001.com/home/?_profileuid=181701569&t=71'
#擴展功能,任何登錄的個人都可以訪問屬於他們自己的個人主頁
basu_url = 'http://www.kaixin001.com/home/?_profileuid=%s&t=71%(uid)'
headers = {
"user_agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
}
req = request.Request(url=basu_url, headers=headers)
# 2
response = opener.open(req)
html = response.read()
html = html.decode('utf-8')
with open('kaixingerenpage','w',encoding='utf-8') as f:
f.write(html)
print(html)
if __name__=='__main__':
account = input("請輸入賬號:")
password = input("請輸入密碼:")
login(account, password)
#登錄后訪問個人主頁
# gerenpage(uid)
————————————————
版權聲明:本文為CSDN博主「Arthur54271」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/zbrj12345/article/details/79929929