程序猿刚子的博客

大龄程序猿,分享互联网开发相关知识!前端、后端,架构等内容,欢迎关注公众号 chengxuyuangangzi

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  96 随笔 :: 14 文章 :: 110 评论 :: 27万 阅读

#coding=gbk
#download pictures of the url
#useage: python downpicture.py www.baidu.com

import os
import sys
from html.parser import HTMLParser
from urllib.request import urlopen
from urllib.parse import urlparse

def 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+1

if __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))

  result:

  num of download pictures is 19

posted on   程序猿刚子  阅读(5542)  评论(7编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示