Python을 사용하여 HTML 페이지 소스에서 이미지 파일을 다운로드 하시겠습니까?

StackOverflow https://stackoverflow.com/questions/257409

  •  05-07-2019
  •  | 
  •  

문제

HTML 페이지에서 모든 이미지 파일을 다운로드하여 특정 폴더에 저장하는 스크레이퍼를 작성하고 있습니다. 모든 이미지는 HTML 페이지의 일부입니다.

도움이 되었습니까?

해결책

다음은 제공된 URL에서 모든 이미지를 다운로드하고 지정된 출력 폴더에 저장하는 코드입니다. 자신의 요구에 맞게 수정할 수 있습니다.

"""
dumpimages.py
    Downloads all the images on the supplied URL, and saves them to the
    specified output file ("/test/" by default)

Usage:
    python dumpimages.py http://example.com/ [output]
"""
from bs4 import BeautifulSoup as bs
from urllib.request import (
    urlopen, urlparse, urlunparse, urlretrieve)
import os
import sys

def main(url, out_folder="/test/"):
    """Downloads all the images at 'url' to /test/"""
    soup = bs(urlopen(url))
    parsed = list(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(urlunparse(parsed), outpath)

def _usage():
    print("usage: python dumpimages.py http://example.com [outpath]")

if __name__ == "__main__":
    url = sys.argv[-1]
    out_folder = "/test/"
    if not url.lower().startswith("http"):
        out_folder = sys.argv[-1]
        url = sys.argv[-2]
        if not url.lower().startswith("http"):
            _usage()
            sys.exit(-1)
    main(url, out_folder)

편집하다: 지금 출력 폴더를 지정할 수 있습니다.

다른 팁

Ryan의 솔루션은 양호하지만 이미지 소스 URL이 절대 URL이거나 단순히 메인 페이지 URL에 연결할 때 좋은 결과를 제공하지 않는 경우 실패합니다. urljoin은 절대 대 상대 URL을 인식하므로 중간의 루프를 다음과 같이 대체하십시오.

for image in soup.findAll("img"):
    print "Image: %(src)s" % image
    image_url = urlparse.urljoin(url, image['src'])
    filename = image["src"].split("/")[-1]
    outpath = os.path.join(out_folder, filename)
    urlretrieve(image_url, outpath)

페이지를 다운로드하고 HTML 문서를 구문 분석하고 Regex로 이미지를 찾고 다운로드해야합니다. 다운로드하기 위해 Urllib2를 사용하고 HTML 파일을 구문 분석 할 수있는 아름다운 수프를 사용할 수 있습니다.

그리고 이것은 하나의 이미지를 다운로드하는 기능입니다.

def download_photo(self, img_url, filename):
    file_path = "%s%s" % (DOWNLOADED_IMAGE_PATH, filename)
    downloaded_image = file(file_path, "wb")

    image_on_web = urllib.urlopen(img_url)
    while True:
        buf = image_on_web.read(65536)
        if len(buf) == 0:
            break
        downloaded_image.write(buf)
    downloaded_image.close()
    image_on_web.close()

    return file_path

htmllib을 사용하여 모든 IMG 태그 (DESTRIDE DO_IMG)를 추출한 다음 urllib2를 사용하여 모든 이미지를 다운로드하십시오.

요청에 권한이 필요한 경우 다음을 참조하십시오.

r_img = requests.get(img_url, auth=(username, password)) 
f = open('000000.jpg','wb') 
f.write(r_img.content) 
f.close()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top