您的位置:首页 > 编程语言 > Python开发

【Python】下载图片的代码

2017-06-21 17:13 513 查看
今天发一段代码,目的是下载某个网址中的图片。

初学Python,随意写的,写的不是很好。

import urllib.request
import os

def url_open(url):
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36')
page = urllib.request.urlopen(req)
html = page.read()

return html

def download_mai():
url = "http://mp.weixin.qq.com/s?__biz=MjM5NDE0ODE2MA==&mid=2652348833&idx=1&sn=a6f776874c8525c524fcc785be5dedec&chksm=bd6f3b8e8a18b298df82421cb2d71c593b4ce72e9704d0cb4e25cf8d43d32aff8d55ab92910c&mpshare=1&scene=5&srcid=0621Km1aj30U60iSQjImdFCd#rd"
html = url_open(url).decode('utf-8')
#print(html)
a = html.find("h2 class=\"rich_media_title\" id=\"") + 47
b = html.find("</h2>", a)

headName = html[a:b].strip().replace("?","")
print(headName)

img_addrs = []
while True:
a = html.find("data-src=" , a)
if a == -1:
break

a = a + 10
b = html.find(" " , a) - 1
name = html[a:b]
if name.find("wx_fmt=gif") != -1:
continue;
img_addrs.append(name)
a = b

a = 0

for each in img_addrs:
print(each)
filename = headName + str(a) + ".png"
a = a + 1

with open(filename, 'wb') as f:
img = url_open(each)
f.write(img)

if __name__ == '__main__':
download_mai()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: