1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

再帰的にリンクを辿って画像スクレイピング

Last updated at Posted at 2019-06-07

beautiful soupを使って、urlから画像のスクレイピングをしてみた。
収集元は乃木坂まとめ(http://nogizaka46matomenoma.blog.jp/)

beutiful soupは結構わかりにくいところなどもあったが、一応できた。

ただ、再帰的にやると同じ画像が多くなる。これを解決する方法あったら誰か教えてください。


from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests


def get_link (url):
    html = urlopen(url)
    soup = BeautifulSoup(html, 'lxml')
    link_list = []
    for i in soup.find_all('a'):
        link = i.get('href')
        if type(link) is str:
            if 'http' in link:
    # javascriptの何か?が混ざっている。よくわからないからtype=strとif ~ in で絞る。
                link_list.append(link)
    return link_list


def link_to_img(url):
    html = urlopen(url)
    soup = BeautifulSoup(html, 'lxml')
    img_list = []
    for i in soup.find_all('img'):
        link = i.get('src')
        img_list.append(link)
    return img_list


url = "http://nogizaka46matomenoma.blog.jp/"

img_name_list = []
for img in img_list:
    try:
        re = requests.get(img)
        if len(img.split('/')[-1]) > 20:
            img_name = img.split('/')[-1][-20:]
        else :
            img_name = img.split('/')[-1]
            with open('./' + img.split('/')[-1], 'wb') as f: # img_listフォルダに格納
                f.write(re.content)
            img_name_list.append(img_name)
    except:
        pass
    

big_pic_list = []
for i in range(len(img_name_list)):
    try:
        pic = Image.open(img_name_list[i])
        if pic.size[0] > 400 and pic.size[1] > 400:
            big_pic_list.append(pic)
    #  高さ、幅それぞれ500以上のものだけをリストにする。
    except:
        pass

nanamin2.png

100枚くらい集まった。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?