今天製做一個優美庫圖片小程序,網址http://www.umei.cc/bizhitupian/
,html
爬蟲的相關流程:獲取目標網址-獲取數據-存儲數據。下面是該網頁的內容:小程序
服務器
對電腦壁紙標籤下的網頁1(<http://www.umei.cc/bizhitupian/diannaobizhi/1.htm>
)與網頁2(<http://www.umei.cc/bizhitupian/diannaobizhi/2.htm>
)進行比較,你會發現只是url中的數字發生改變,因此咱們能夠模擬構造url,進行圖片連接的抓取。多線程
代碼段:app
1 import requests 2 from lxml import etree 3 import re 4 from urllib.request import urlretrieve 5 import random 6 dict = {} 7 img_url = [] 8 img = [] 9 10 headers = { 11 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36' 12 } 13 def Total_label(): 14 '''獲取標籤並進行分類存放在字典中''' 15 response = requests.get('http://www.umei.cc/bizhitupian/').content 16 html = etree.HTML(response) 17 18 title = html.xpath("//div[@class='w850 l oh']//a/@title") 19 url = html.xpath("//div[@class='w850 l oh']//a/@href") 20 # 循環鑲嵌將標題與url結合 21 index = 0 22 for i in title: 23 dict[i] = url[index] 24 index += 1 25 # for k, v in dict.items(): 26 # print(k , v) 27 # 抓取連接 28 def Grab(num): 29 '''獲取每一個標籤下的總頁數''' 30 url = dict[num] 31 # print(url) 32 response = requests.get(url,headers=headers,timeout=3) 33 # response.encoding = 'utf-8' 34 text = response.content.decode('utf-8') 35 html = etree.HTML(text) 36 pages = html.xpath("//div[@class='NewPages']//ul/li//@href")[-1].split('.')[0] 37 return (int(pages),url) 38 39 # 獲取總頁中全部分頁的url 40 def get_paging(url,pages_n): 41 urls = [url+'{}.htm'.format(i) for i in range(1,pages_n+1)] 42 '''獲取每一個url下的圖片連接''' 43 for i in urls: 44 response_time = requests.get(i, headers=headers, timeout=3) 45 # response.encoding = 'utf-8' 46 text = response_time.content.decode('utf-8') 47 html = etree.HTML(text) 48 jpg_url = html.xpath("//div[@class='TypeList']//a/@href") 49 for i in jpg_url: 50 img_url.append(i)
第二步:咱們已經有了分頁的url,咱們再獲取圖片的url,進行下載便可:dom
1 def img_To_obtain(): 2 '''圖片獲取''' 3 # 圖片連接 Xpath語法://*[@id="ArticleId60"]/p/a/img/@src 4 # print(img_url) 5 for x in img_url: 6 response = requests.get(x,headers=headers,timeout=3) 7 text = response.content.decode('utf-8') 8 html = etree.HTML(text) 9 '''整站爬,分頁,能夠經過url進行判斷 10 if 頁數2 == 網頁狀態404: 11 只是一張圖片 12 該系列有分頁 13 ''' 14 page_f = html.xpath('//*[@id="ArticleId60"]/p/a/img/@src') 15 for j in page_f: 16 img.append(j) 17 18 def extract(): 19 '''隨機獲取一張圖片''' 20 IMAGE_URL = random.choice(img) 21 The_suffix = IMAGE_URL.split('.')[3] 22 urlretrieve(IMAGE_URL, './image/img1.{}'.format(The_suffix))
主程序部分:學習
1 if __name__ == '__main__': 2 print('================歡迎來到圖片選擇器v1.0=====================') 3 print('''=====================提示信息============================= 4 1:電腦壁紙 5 2:手機壁紙 6 3.動態壁紙 7 。。。。 8 9:可愛壁紙 9 ''') 10 Total_label() 11 num = str(input("請輸入您的選擇:")) 12 '''頁數+標題url''' 13 page_n,url = Grab(num) 14 print('%s頁數爲:%s, url:%s'%(num,page_n,url)) 15 get_paging(url,page_n) 16 extract()
實現效果:網站
結尾:url
該程序比較低級,能夠說很垃圾,小編本身都感受很垃圾,有不少沒有完善的地方,使用的面向過程的,沒有多線程,沒有異常處理,代碼囉嗦等。spa
勝在學習思路吧,該網站是沒有反爬的,基本網站,可是不要過分的請求,給對方服務器留條活路,後期會把完善的代碼重作一期跟你們一塊兒學習。