繁体   English   中英

如何使用python从网页下载文件

[英]How to download files from a webpage using python

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

我的第一个函数是一个wget函数,它读取网页并将其分配给变量。 我的第二个函数是一个RegEx,它在webpages 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)下载这些文件的函数,但我不知道如何解决这个问题,主要是因为某些输出是绝对路径,而其他的是相对的。 我也不确定如何同时下载所有这些并下载,而不必每次都指定名称和位置。

Path-Agnostic获取资源(可以处理绝对/相对路径) -

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/')

我不能给你写完整的代码,我确信这不是你想要的,但这里有一些提示:

1) 不要与解析正则表达式随机HTML页面,就表示该做相当多的解析器。 我建议BeautifulSoup 您将过滤所有img元素并获取其src值。

2)使用src值,您可以按照自己的方式下载文件。 关于相对/绝对问题,请使用urlparse模块,根据此SO答案 我们的想法是将图像的src与您下载HTML的URL相连接。 如果src已经是绝对的,它将保持这种状态。

3)至于全部下载,只需遍历要从中下载图像的网页列表,并对每个页面中的每个图像执行步骤1和2。 当你说“同时”时,你可能意味着异步下载它们。 在这种情况下,我建议在一个帖子中下载每个网页。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM