python爬取图片然后保存在文件夹中
直接上代码:
import osimport requestsimport redef getimg(soup,i):print('http:'+ soup[0])root = "D://tu//tu" # 保存的根目录j=1for k in soup:print(k)path = root + str(j) + ".jpg" # 保存的地址if not os.path.exists(path): # 如果文件不存在就爬取并保存mun='http:'+ kr=requests.get(mun)j=j+1with open(path, 'wb') as f: # 'wb'以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。f.write(r.content) # content返回二进制数据,所以使用'wb'f.close()print("文件保存成功")else:print("文件已存在")def main():url = '/search?q=%E8%AE%A1%E7%AE%97%E6%9C%BA%E7%BD%91%E7%BB%9C&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_2026&ie=utf8'file = open('C:/Users/YHAA-1ED2A3/Desktop/taobao_product.txt','w',encoding='utf-8')cookie_str = r't=e62fc3896f26735342c795d27a369781; c83ebeb; xlly_s=1; 'cookies = {}headers = {'User-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'}for line in cookie_str.split(';'):key, value = line.split('=', 1)cookies[key] = valuer = requests.get(url, headers = headers, cookies = cookies)r.encoding = r.apparent_encodingdemo = r.textsoup = re.findall(r'"pic_url":"([^"]+)"',r.text,re.I) getimg(soup,1)main()
结果:
如果觉得《python爬取图片然后保存在文件夹中》对你有帮助,请点赞、收藏,并留下你的观点哦!