国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python實現(xiàn)下載指定網(wǎng)址所有圖片的方法

2019-11-25 17:05:54
字體:
供稿:網(wǎng)友

本文實例講述了python實現(xiàn)下載指定網(wǎng)址所有圖片的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

#coding=utf-8#download pictures of the url#useage: python downpicture.py www.baidu.comimport osimport sysfrom html.parser import HTMLParserfrom urllib.request import urlopenfrom urllib.parse import urlparsedef getpicname(path):  '''  retrive filename of url    '''  if os.path.splitext(path)[1] == '':    return None  pr=urlparse(path)  path='http://'+pr[1]+pr[2]  return os.path.split(path)[1]def saveimgto(path, urls):  '''  save img of url to local path  '''  if not os.path.isdir(path):    print('path is invalid')    sys.exit()  else:    for url in urls:      of=open(os.path.join(path, getpicname(url)), 'w+b')      q=urlopen(url)      of.write(q.read())      q.close()      of.close()class myhtmlparser(HTMLParser):  '''put all src of img into urls'''  def __init__(self):    HTMLParser.__init__(self)    self.urls=list()    self.num=0  def handle_starttag(self, tag, attr):    if tag.lower() == 'img':      srcs=[u[1] for u in attr if u[0].lower() == 'src']      self.urls.extend(srcs)      self.num = self.num+1if __name__ == '__main__':  url=sys.argv[1]  if not url.startswith('http://'):    url='http://' + sys.argv[1]  parseresult=urlparse(url)  domain='http://' + parseresult[1]  q=urlopen(url)  content=q.read().decode('utf-8', 'ignore')  q.close()  myparser=myhtmlparser()  myparser.feed(content)  for u in myparser.urls:    if (u.startswith('//')):      myparser.urls[myparser.urls.index(u)]= 'http:'+u    elif u.startswith('/'):      myparser.urls[myparser.urls.index(u)]= domain+u  saveimgto(r'D:/python/song', myparser.urls)  print('num of download pictures is {}'.format(myparser.num))

運行結(jié)果如下:

num of download pictures is 19

希望本文所述對大家的Python程序設(shè)計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 浮梁县| 澄城县| 香格里拉县| 冀州市| 清新县| 镇宁| 文昌市| 汉中市| 汶上县| 固阳县| 衡阳市| 克山县| 买车| 龙海市| 赣州市| 永嘉县| 兰溪市| 蓬溪县| 大安市| 安庆市| 且末县| 习水县| 同仁县| 通河县| 华坪县| 尚义县| 天门市| 襄城县| 上林县| 佛坪县| 田东县| 漾濞| 长乐市| 永安市| 新源县| 崇左市| 呼图壁县| 海淀区| 汤阴县| 阿拉尔市| 怀仁县|