美文网首页
05存储数据

05存储数据

作者: 李慕玄 | 来源:发表于2018-04-14 08:38 被阅读0次

Python3中,urllib.request.urlretrieve根据文件的URL下载文件。

程序从http://pythonscraping.com下载logo图片,然后在程序运行的文件夹里保存为logo.jpg文件。

from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://pythonscraping.com")
bsObj = BeautifulSoup(html)
imageLocation = bsObj.find("a", {"id":"logo"}).find("img")["src"]
urlretrieve(imageLocation, "logo.jpg")

程序把http://pythonscraping.com上所有src属性的文件都下载:

import os
from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup

downloadDirectory = "downloaded"
baseUrl = "http://pythonscraping.com"

def getAbsoluteURL(baseUrl, source):
    if source.startswith("http://www."):
        url = "http://" + source[11:]
    elif source.startswith("http://"):
        url = source
    elif source.startswith("www."):
        url = "http://" source[4:]
    else:
        url = baseUrl + "/" + source
    if baseUrl not in url:
        return None
    return url

del getDownloadPath(baseUrl, absoluteUrl, downloadDirectory):
    path = absoluteUrl.replace("www.", "")
    path = path.replace(baseUrl, "")
    path = downloadDirectory+path
    directory = os.path.dirname(path)

    if not os.path.exists(directory):
        os.makedirs(directory)

    return path

html = urlopen("http://pythonscraping.com")
bsObj = BeautifulSoup(html)
downloadList = bsObj.findAll(src=True)

for download in downloadList:
    fileUrl = getAbsoluteURL(baseUrl, download["src"])
    if fileUrl is not None:
        print(fileUrl)
        urlretrieve(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory))

相关文章

  • 05存储数据

    Python3中,urllib.request.urlretrieve根据文件的URL下载文件。 程序从http:...

  • 数据库技术

    数据库技术 sschrodinger 2019/05/06 引用 MySQL 技术内幕 - InnoDB 存储引擎...

  • Oracle存储过程

    2019-05-13 存储过程是用来完成指定任务的程序,存储在数据库系统中,用户可以远程调用存储过程。 存储过程的...

  • BMOB云端逻辑的一些坑(操作数据库的一些坑)

    Date数据类型的存储:{"__type":"Date", "iso":"2015-05-13 14:20:10"...

  • HADOOP 3.0.0 之 HDFS RAID

    author: fenqi@mogujiedate: 2016/05/19 背景 场景1:实时访问冷数据存储 场景...

  • 05-iOS数据存储

    一、iOS沙盒机制 iOS的每个应用都有属于自己的存储空间,即沙盒应用只能访问自己的沙盒,不可访问其他区域。 沙盒...

  • Android入门05 -- 数据存储

    Android的数据存储方式有:SharedPreferences,File,SQLite,下面来详细介绍每种数据...

  • Android ContentProvider(一)

    Android数据存储(一) Android数据存储(二) Android数据存储(三) Android数据存储(...

  • day07

    Android的存储方式 使用SharedPreferences存储数据 文件存储数据 SQLite数据库存储数据...

  • 【技术栈】【面试】技术栈拆分及比重

    01 Java基础 02 Java难点 03 数据存储 04 计算机基础 05 应用技术 06 分布式技术 07 ...

网友评论

      本文标题:05存储数据

      本文链接:https://www.haomeiwen.com/subject/vipkkftx.html