【Python3爬蟲-爬圖片】多執行緒爬取中國國家地理全站美圖,多圖可以提高你的審美哦
阿新 • • 發佈:2018-11-20
宣告:爬蟲為學習使用,請各位同學務必不要對當放網站或i伺服器造成傷害。務必不要寫死迴圈。
-
思路:古鎮——古鎮列表(迴圈獲取古鎮詳情href)——xx古鎮詳情(獲取所有img的src)
-
1. 單分類爬:
from bs4 import BeautifulSoup import urllib.request import requests import os import re # 儲存文章裡面的圖片 def down(url, num): # 獲取網頁 response = urllib.request.urlopen(url) html = response.read().decode('utf-8') # 編碼格式gb2312,utf-8,GBK html_string = str(html) # 轉換成string,可以直接向資料庫新增 soup = BeautifulSoup(html_string, "html.parser") # 解析網頁標籤 # 匹配抓取區域 # 該div的class由img和aImg兩種,要判斷一下 pid = soup.findAll('div', {"class": "img"}) if len(pid) == 0: pid = soup.findAll('div', {"class": "aImg"}) pass print(pid) pid2 = soup.find("article").find("h1") # 本篇文章的標題 # 清除html標籤 pattern = re.compile(r'<[^>]+>', re.S) txt = pattern.sub('', str(pid2)) print(txt) for img_html in pid: img_src = img_html.find('img')['src'] root = "D:/python/do/spider/guojiadili/" + txt + "/" # 沒有最後一級資料夾目錄則會自動建立 img_name = img_src.split("/")[-1].replace('@!rw9', '').replace('@!rw14', '').replace('@!rw7', '').replace('@!rw8', '').replace('@!rw10', '').replace('@!rw11', '').replace('@!rw12', '').replace('@!rw13', '').replace('@!rw6', '').replace('@!rw5', '').replace('@!rw4', '').replace('@!rw3', '').replace('@!rw2', '').replace('@!rw1', '').replace('@!rw15', '').replace('@!rw16', '').replace('@!rw17', '').replace('@!rw18', '').replace('@!rw19', '') # 去除圖片字尾後面的特殊字串,得到真實圖片名 print(img_name) path = root + img_name # 儲存檔案的名字 # 儲存圖片到本地 try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(img_src) r.raise_for_status() # 使用with語句可以不用自己手動關閉已經開啟的檔案流 with open(path, "wb") as f: # 開始寫檔案,wb代表寫二進位制檔案 f.write(r.content) num += 1 print("儲存檔案成功=" + str(num)) else: print("檔案已存在") except Exception as e: print("檔案儲存失敗:" + str(e)) pass pass # down("http://www.dili360.com//article/p549a356731fc659.htm", 0) # 解析文章目錄中所有的文章地址 def list(url, number): # 獲取網頁 response = urllib.request.urlopen(url) html = response.read().decode('utf-8') # 編碼格式gb2312,utf-8,GBK html_string = str(html) # 轉換成string,可以直接向資料庫新增 soup = BeautifulSoup(html_string, "html.parser") # 解析網頁標籤 # 匹配抓取區域 # pid = soup.find(attrs={"id": "content"}) pid = soup.findAll('div', {"class": "thumb-img"}) print(pid) print("第" + str(number) + "頁") for a_html in pid: a_href = a_html.find('a')['href'] print(a_href) new_url = "http://www.dili360.com" + a_href # 文章地址 print(new_url) print(type(new_url)) down(new_url, 0) # 獲取單個列表中單個文章的圖片 pass pass # list('http://www.dili360.com/Travel/sight/20194/1.htm') # 解析有多少個文章目錄 page = 1 # 起始目錄標號 while page <= 14: # 最大目錄標號 list('http://www.dili360.com/Travel/sight/20247/' + str(page) + '.htm', 1) # 單個目錄地址 page += 1 pass else: print("所有文章儲存完畢!")
-
提示,迴圈sight/xxxxx.htm可以把整個分類全部爬下來。但是不建議你這樣學習。爬個上G圖片也沒什麼用處。
-
旅遊就去這些古鎮吧!
-
2. 以下是爬單程序爬取全站圖片(過幾天做圖片分用):
from bs4 import BeautifulSoup import urllib.request import requests import os import re # 儲存文章裡面的圖片 def down(url, num, file): # 獲取網頁 response = urllib.request.urlopen(url) html = response.read().decode('utf-8') # 編碼格式gb2312,utf-8,GBK html_string = str(html) # 轉換成string,可以直接向資料庫新增 soup = BeautifulSoup(html_string, "html.parser") # 解析網頁標籤 # 匹配抓取區域 # 該div的class由img和aImg兩種,要判斷一下 pid = soup.findAll('div', {"class": "img"}) if len(pid) == 0: pid = soup.findAll('div', {"class": "aImg"}) pass print(pid) pid2 = soup.find("article").find("h1") # 本篇文章的標題 # 清除html標籤 pattern = re.compile(r'<[^>]+>', re.S) txt = pattern.sub('', str(pid2))[0:20] print(txt) for img_html in pid: img_src = img_html.find('img')['src'] root_file = "D:/python/do/spider/guojiadili/" + file + "/" # 分類的資料夾 root = root_file + txt + "/" # 沒有最後一級資料夾目錄則會自動建立 img_name = img_src.split("/")[-1].replace('@!rw9', '').replace('@!rw14', '').replace('@!rw7', '').replace('@!rw8', '').replace('@!rw10', '').replace('@!rw11', '').replace('@!rw12', '').replace('@!rw13', '').replace('@!rw6', '').replace('@!rw5', '').replace('@!rw4', '').replace('@!rw3', '').replace('@!rw2', '').replace('@!rw1', '').replace('@!rw15', '').replace('@!rw16', '').replace('@!rw17', '').replace('@!rw18', '').replace('@!rw19', '') # 去除圖片字尾後面的特殊字串,得到真實圖片名 print(img_name) path = root + img_name # 儲存檔案的名字 # 儲存圖片到本地 try: if not os.path.exists(root_file): os.mkdir(root_file) if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(img_src) r.raise_for_status() # 使用with語句可以不用自己手動關閉已經開啟的檔案流 with open(path, "wb") as f: # 開始寫檔案,wb代表寫二進位制檔案 f.write(r.content) num += 1 print("儲存檔案成功=" + str(num)) else: print("檔案已存在") except Exception as e: print("檔案儲存失敗:" + str(e)) pass pass # down("http://www.dili360.com//article/p549a356731fc659.htm", 0) # 解析文章目錄中所有的文章地址 def list(url, number): print(url) # 獲取網頁 response = urllib.request.urlopen(url) html = response.read().decode('utf-8') # 編碼格式gb2312,utf-8,GBK html_string = str(html) # 轉換成string,可以直接向資料庫新增 soup = BeautifulSoup(html_string, "html.parser") # 解析網頁標籤 try: # 匹配抓取區域 # pid = soup.find(attrs={"id": "content"}) pid = soup.findAll('div', {"class": "thumb-img"}) print(pid) pid2 = soup.find(attrs={"class": "article-left"}).find("h1") # 分類的標題 print(pid2) # 清除html標籤 pattern = re.compile(r'<[^>]+>', re.S) file = pattern.sub('', str(pid2))[0:20] print("第" + str(number) + "頁") for a_html in pid: a_href = a_html.find('a')['href'] print(a_href) new_url = "http://www.dili360.com" + a_href # 文章地址 print(new_url) print(type(new_url)) down(new_url, 0, file) # 獲取單個列表中單個文章的圖片 pass except: print("無該頁面") pass pass # list('http://www.dili360.com/Travel/sight/20194/1.htm') # list('http://www.dili360.com/travel/sight/20281.htm', 0) # list('http://www.dili360.com/travel/sight/' + str(class_num) + '/' + str(1) + '.htm', 1) # 單個目錄地址 def page_class(): for cla in range(20190, 20290): for page in range(1, 30): list('http://www.dili360.com/travel/sight/' + str(cla) + '/' + str(page) + '.htm', 1) # 單個目錄地址 pass pass pass page_class() pass
-
3. 以下是多執行緒爬,有多少個分類就有多少個執行緒:
from bs4 import BeautifulSoup import urllib.request import requests import os import re import time import _thread # 儲存文章裡面的圖片 def down(url, num, file): # 獲取網頁 response = urllib.request.urlopen(url) html = response.read().decode('utf-8') # 編碼格式gb2312,utf-8,GBK html_string = str(html) # 轉換成string,可以直接向資料庫新增 soup = BeautifulSoup(html_string, "html.parser") # 解析網頁標籤 # 匹配抓取區域 # 該div的class由img和aImg兩種,要判斷一下 pid = soup.findAll('div', {"class": "img"}) if len(pid) == 0: pid = soup.findAll('div', {"class": "aImg"}) pass print(pid) pid2 = soup.find("article").find("h1") # 本篇文章的標題 # 清除html標籤 pattern = re.compile(r'<[^>]+>', re.S) txt = pattern.sub('', str(pid2))[0:20] print(txt) for img_html in pid: img_src = img_html.find('img')['src'] root_file = "D:/python/do/spider/guojiadili/" + file + "/" # 分類的資料夾 root = root_file + txt + "/" # 沒有最後一級資料夾目錄則會自動建立 img_name = img_src.split("/")[-1].replace('@!rw9', '').replace('@!rw14', '').replace('@!rw7', '').replace('@!rw8', '').replace('@!rw10', '').replace('@!rw11', '').replace('@!rw12', '').replace('@!rw13', '').replace('@!rw6', '').replace('@!rw5', '').replace('@!rw4', '').replace('@!rw3', '').replace('@!rw2', '').replace('@!rw1', '').replace('@!rw15', '').replace('@!rw16', '').replace('@!rw17', '').replace('@!rw18', '').replace('@!rw19', '') # 去除圖片字尾後面的特殊字串,得到真實圖片名 print(img_name) path = root + img_name # 儲存檔案的名字 # 儲存圖片到本地 try: if not os.path.exists(root_file): os.mkdir(root_file) if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r = requests.get(img_src) r.raise_for_status() # 使用with語句可以不用自己手動關閉已經開啟的檔案流 with open(path, "wb") as f: # 開始寫檔案,wb代表寫二進位制檔案 f.write(r.content) num += 1 print("儲存檔案成功=" + str(num)) else: print("檔案已存在") except Exception as e: print("檔案儲存失敗:" + str(e)) pass pass # down("http://www.dili360.com//article/p549a356731fc659.htm", 0) # 解析文章目錄中所有的文章地址 def list(url, number): print(url) # 獲取網頁 response = urllib.request.urlopen(url) html = response.read().decode('utf-8') # 編碼格式gb2312,utf-8,GBK html_string = str(html) # 轉換成string,可以直接向資料庫新增 soup = BeautifulSoup(html_string, "html.parser") # 解析網頁標籤 try: # 匹配抓取區域 # pid = soup.find(attrs={"id": "content"}) pid = soup.findAll('div', {"class": "thumb-img"}) print(pid) pid2 = soup.find(attrs={"class": "article-left"}).find("h1") # 分類的標題 print(pid2) # 清除html標籤 pattern = re.compile(r'<[^>]+>', re.S) file = pattern.sub('', str(pid2))[0:20] print("第" + str(number) + "頁") for a_html in pid: a_href = a_html.find('a')['href'] print(a_href) new_url = "http://www.dili360.com" + a_href # 文章地址 print(new_url) print(type(new_url)) down(new_url, 0, file) # 獲取單個列表中單個文章的圖片 pass except: print("無該頁面") pass pass # 單執行緒爬 # def page_class(): # # for cla in range(20190, 20290): # for page in range(1, 30): # list('http://www.dili360.com/travel/sight/' + str(cla) + '/' + str(page) + '.htm', 1) # 單個目錄地址 # pass # pass # # pass # # # page_class() # pass # 多執行緒爬,有多少個分類就有多少執行緒 all_thread_num = 0 def page_class(cla, that_num): # print("已啟動執行緒=" + str(that_num)) global all_thread_num all_thread_num += 1 print("執行緒總數=" + str(all_thread_num)) for page in range(1, 30): list('http://www.dili360.com/travel/sight/' + str(cla) + '/' + str(page) + '.htm', 1) # 單個目錄地址 pass pass for cla in range(20190, 20291): # 建立執行緒 try: _thread.start_new_thread(page_class, (cla, (cla - 20000))) # page_class(cla, (cla - 20000)) pass except: print("無法啟動執行緒") pass pass while 1: pass
只有17593張圖片嗎????3342篇有分類的博客遊記???懷疑人生!
-