圖片上傳
-
網站原始碼
https://github.com/jeankao/plant
上傳表單
http://drweb.nksh.tp.edu.tw/upload/
機器人程式:將圖片用程式上傳到網站
import requests from html.parser import HTMLParser # Helper class to parse CSRF token from response class CSRFTokenParser(HTMLParser): csrftoken = "" def handle_starttag(self, tag, attrs): if tag == "input": keep = False for attr in attrs: if attr[0] == 'name' and attr[1] == 'csrfmiddlewaretoken': keep = True elif attr[0] == 'value' and keep: self.csrftoken = attr[1] def get_token(self): return self.csrftoken # --------------------------------------------------------------------------- # Upload Data configuration test_url = 'http://drweb.nksh.tp.edu.tw/upload/' mac_addr = '00:00:00:00:00:00' upload_file_path = '2-Blog-HeroImage-1024x576.png' # file to upload # Phase 1: Get CSRF Token & cookies rs = requests.session() response = rs.get(test_url) parser = CSRFTokenParser() parser.feed(response.text) # Phase 2: Upload file upload_data = { 'csrfmiddlewaretoken': (None, parser.get_token()), 'mac_address': (None, mac_addr), 'image': ('img.png', open(upload_file_path, 'rb'), 'image/png'), } response = requests.post(test_url, files = upload_data, cookies = response.cookies) # Debug output out = open("result.html", "w") out.write(response.text) out.close() print(response.text)