2016-04-26 10 views
0

python画像クローラを作成したいと思います。imgae srcを取得し、python image crawlerで画像をディレクトリに保存する

これは私が今持っているものです。

from bs4 import BeautifulSoup 
from urllib.request import urlopen 
url = 'http://blog.pouyacode.net/' 
data = urlopen(url) 
soup = BeautifulSoup(data, 'html.parser') 
img = soup.findAll('img') 
print (img) 
print ('\n') 
print ('****************************') 
print ('\n') 
for each in img: 
    print(img.get('src')) 
    print ('\n') 

この部分は動作します:

print (img) 
print ('\n') 
print ('****************************') 
print ('\n') 

しかし、出力の*****************後に、このエラーが表示されます:

Traceback (most recent call last): 
File "pull.py", line 15, in <module> 
print(img.get('src')) 
AttributeError: 'ResultSet' object has no attribute 'get' 

だから、どのようにすることができます私はすべての画像のすべてのSRCを取得しますか? これらの画像をディレクトリに保存するにはどうすればよいですか?

+1

をテストしていない代わりに、img.getの(「SRC」)(「SRC」) – Zillolo

+0

はい、申し訳ありませんそれは少し間違いでした!ありがとうございました。しかし、2番目のものはどうですか?フォルダに画像を保存しますか? – niloofar

答えて

2

これは何か?あなたはおそらくeach.getを使用することを意味心から書かれており、

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

url = 'http://blog.pouyacode.net/' 
download_folder = "downloads" 

if not os.path.exists(download_folder): 
    os.makedirs(download_folder) 

data = urlopen(url) 
soup = BeautifulSoup(data, 'html.parser') 
img = soup.findAll('img') 

for each in img: 
    url = each.get('src') 
    data = urlopen(url) 
    with open(os.path.join(download_folder, os.path.basename(url)), "wb") as f: 
     f.write(data.read()) 
+0

はいはいはい!!!!!!とてもありがとう@salmonderossi :) – niloofar

+1

@niloofarよろしくお願いします。私は少し私の答えをきれいにした... – salomonderossi

関連する問題