Content finishing MOOC-- Beijing Institute of Technology, China University Self - Artemisia days -Python web crawler and information extraction
Use requests.get () method crawling web picture and save it to local
. 1 Import Requests 2 . 3 path = " D: /picture.jpg " # set the saving path . 4 URL = " http://img.kitstown.com/news/2020/01/20psg4th.jpg " # Web Image Path . 5 R & lt = requests.get (url) 6 Print (r.status_code) 7 with Open (path, " wb " ) AS f: 8 f.write (r.content) # returns the binary content written to the file (that is, the actual picture crawling to the local)
For further optimize the code, the file name stored in the local file name is the same as the original, and adding an exception to remind
import requests import os URL = " http://img.kitstown.com/news/2020/01/20psg4th.jpg " the root = " D: // // pics " # Set save directory path = + url.split the root ( ' / ' ) [-1] # picture of the original file name used for local naming the try : iF not os.path.exists (root): # determine the current root directory exists os.mkdir (root) iF not os.path.exists (path ): # determines whether the current file is present R & lt = requests.get (URL) with open(path,'wb') as f: f.write(r.content) f.close() Print ( " File saved successfully " ) the else : Print ( " file already exists " ) the except : Print ( " crawling failure " )