如何在Python中获取网页及其图片

8 投票
2 回答
3401 浏览
提问于 2025-04-17 01:31

我想获取一个网页的内容,包括里面的图片。目前我有这个:

import urllib

page = urllib.urlretrieve('http://127.0.0.1/myurl.php', 'urlgot.php')
print urlgot.php

这个代码可以很好地获取网页内容,但我还需要下载所有链接的图片。

我在想,能不能写一个正则表达式,去查找下载的内容中的img src或者类似的东西;不过,我也在想有没有urllib的函数可以直接获取这些图片?就像wget命令那样:

wget -r --no-parent http://127.0.0.1/myurl.php

我不想使用os模块来运行wget,因为我希望这个脚本能在所有系统上运行。因此,我也不能使用任何第三方模块。

非常感谢任何帮助!谢谢!

2 个回答

3

使用BeautifulSoup这个工具来解析返回的HTML内容,并寻找里面的图片链接。你可能还需要递归地获取框架和内嵌框架(iframes)。

7

在Python中,有一个非常好用的解析器,所以不要使用正则表达式。

from urllib.request import urlretrieve  # Py2: from urllib
from html.parser import HTMLParser      # Py2: from HTMLParser

base_url = 'http://127.0.0.1/'

class ImgParser(HTMLParser):
    def __init__(self, *args, **kwargs):
        self.downloads = []
        HTMLParser.__init__(self, *args, **kwargs)

    def handle_starttag(self, tag, attrs):
        if tag == 'img':
            for attr in attrs:
                if attr[0] == 'src':
                    self.downloads.append(attr[1])

parser = ImgParser()
with open('test.html') as f:
    # instead you could feed it the original url obj directly
    parser.feed(f.read())

for path in parser.downloads:
    url = base_url + path
    print(url)
    urlretrieve(url, path)

撰写回答