[python應用]python簡單圖片抓取


前言

emmmm

python簡單圖片抓取

 

 1 import requests
 2 import threading
 3 import queue
 4 from subprocess import Popen,PIPE
 5 from bs4 import BeautifulSoup as bs
 6 import urllib
 7 import base64
 8 
 9 
10 queue=queue.Queue()
11 
12 class Jiandan(threading.Thread):
13         def __init__(self,queue):
14             threading.Thread.__init__(self)
15             self._queue=queue
16             
17         def run(self):
18             while not self._queue.empty():
19                 url=self._queue.get_nowait()
20                 self.spider(url)
21                 
22         def spider(self,url):
23             headers={}
24             r=requests.get(url)
25             #選擇lxml解析器
26             soup=bs(r.content,'lxml')
27             #查找html標簽name為img的元素獲取到它
28             imgs=soup.find_all(name='img',attrs={})
29             
30             for img in imgs:
31                 if 'onload' in str(img):
32                     img=img['org_src']
33                 else:
34                     img=img['src']
35                 
36                 name=img.split('/')[-1]
37                 
38                 #獲取的url沒http:所以要加上http協議才能訪問下載
39                 img="http:"+img
40                 
41                 #存儲圖片的路徑地址
42                 lu="C:\\Users\\xhds1\\Desktop\\img\\"+name
43                 print(lu)
44                 urlretrieve(img,lu)  #urlretrieve模塊下載圖片
45                # print(name)
46                 
47 def main():
48     sss=""
49     for i in range(137,139):
50         riqi="20200121-%s"%(i)
51         
52         #使用了base64模塊進行URL編碼  這里遇到的問題是編碼后就成為了字節流類型 
53         #查了資料才得知必須轉換成字符串類型才行 糾結了好久
54         strbs=base64.b64encode(riqi.encode(encoding="utf-8")).decode("utf-8") 
55       
56         queue.put("https://jandan.net/pic/"+strbs+"#comments")
57                   
58     threads=[]
59     thread_count=5
60     
61     for i in range(thread_count):
62         threads.append(Jiandan(queue))
63     for t in threads:
64         t.start()
65     for t in threads:
66         t.join()
67         
68 if __name__=='__main__':
69     main()

 

 

參考學習:

淺析Python3中的bytes和str類型:https://www.cnblogs.com/chownjy/p/6625299.html  

 https://www.cnblogs.com/OliverQin/p/8641700.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM