2

重複の可能性:
リクエストを使用して画像をダウンロードする方法

tumblr ブログの画像 URL をスクレイピングするための Python スクリプトがあり、それらをデスクトップのローカル フォルダーにダウンロードしたいと考えています。これを実装するにはどうすればよいですか

import requests 
from bs4 import BeautifulSoup 

def make_soup(url):
#downloads a page with requests and creates a beautifulsoup object

    raw_page = requests.get(url).text
    soup = BeautifulSoup(raw_page)

    return soup


def get_images(soup):
#pulls images from the current page

    images = []

    foundimages = soup.find_all('img')

    for image in foundimages:
        url = img['src']

        if 'media.tumblr.com' in url:
            images.append(url)


    return images


def scrape_blog(url):
# scrapes the entire blog

    soup = make_soup(url)

    next_page = soup.find('a' id = 'nextpage')

    while next_page is not none:

        soup = make_soup(url + next_page['href'])
        next_page = soup.find('a' id = 'nextpage')

        more_images = get_images(soup)
        images.extend(more_images)

    return images


url = 'http://x.tumblr.com'
images = scrape_blog(url)
4

1 に答える 1

1

Python の " urllib2 " はおそらくあなたが探しているものです。複雑なこと (Cookie や認証など) を行う必要がある場合は、Requestsなどのラッパー ライブラリを検討する価値があるかもしれません。これは、標準ライブラリのより面倒な機能の多くの優れたラッパーを提供します。

于 2013-01-01T00:35:23.990 に答える