【问题标题】:How to download files from a webpage using python如何使用python从网页下载文件
【发布时间】:2017-04-09 03:20:24
【问题描述】:

我正在尝试创建一个脚本来抓取网页并下载找到的任何图像文件。

我的第一个函数是读取网页并将其分配给变量的 wget 函数。 我的第二个函数是在网页 html 中搜索“ssrc=”的正则表达式,函数如下:

def find_image(text):
    '''Find .gif, .jpg and .bmp files'''
    documents = re.findall(r'\ssrc="([^"]+)"', text) 
    count = len(documents)
    print "[+] Total number of file's found: %s" % count
    return '\n'.join([str(x) for x in documents])

这个输出是这样的:

example.jpg
image.gif
http://www.webpage.com/example/file01.bmp

我正在尝试编写第三个函数,该函数使用 urllib.urlretrieve(url, filename) 下载这些文件,但我不知道该怎么做,主要是因为一些输出是绝对路径,而其他输出是相对路径。我也不确定如何同时下载所有这些并下载,而无需每次都指定名称和位置。

【问题讨论】:

标签: python html-parsing


【解决方案1】:

与路径无关的资源获取(可以处理绝对/相对路径) -

from bs4 import BeautifulSoup as bs
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os

def fetch_url(url, out_folder="test/"):
    """Downloads all the images at 'url' to /test/"""
    soup = bs(urlopen(url))
    parsed = list(urlparse.urlparse(url))

    for image in soup.findAll("img"):
        print "Image: %(src)s" % image
        filename = image["src"].split("/")[-1]
        parsed[2] = image["src"]
        outpath = os.path.join(out_folder, filename)
        if image["src"].lower().startswith("http"):
            urlretrieve(image["src"], outpath)
        else:
            urlretrieve(urlparse.urlunparse(parsed), outpath)

fetch_url('http://www.w3schools.com/html/')

【讨论】:

    【解决方案2】:

    我无法为您编写完整的代码,我确定这也不是您想要的,但这里有一些提示:

    1) 使用正则表达式解析随机 HTML 页面,有很多解析器为此而生。我建议BeautifulSoup。您将过滤所有img 元素并获取它们的src 值。

    2) 使用现有的src 值,您可以按照现有方式下载文件。关于相对/绝对问题,按照this SO answer 使用urlparse 模块。这个想法是将图像的src 与您从中下载 HTML 的 URL 连接起来。如果src 已经是绝对的,它将保持这种状态。

    3) 至于全部下载,只需遍历您要从中下载图像的网页列表,然后为每个页面中的每个图像执行步骤 1 和 2。当您说“同时”时,您可能是指异步下载它们。那样的话,我建议下载每个网页in one thread

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2017-03-13
      相关资源
      最近更新 更多