2016-06-13 14 views
1

これは4chansの写真板からの画像を擦ります。問題は、同じ画像を2度擦ってしまうことです。なぜ誰かが私を助けてくれるのなら、私は重複した写真を手に入れているのを知ることができません。Python Beautifulsoup重複したエントリの

from bs4 import BeautifulSoup 
import requests 
import re 
import urllib2 
import os 


def get_soup(url,header): 
    return BeautifulSoup(urllib2.urlopen(urllib2.Request(url, headers=header)), 'lxml') 

image_type = "image_name" 
url = "http://boards.4chan.org/p/" 
url = url.strip('\'"') 
print url 
header = {'User-Agent': 'Mozilla/5.0'} 
r = requests.get(url) 
html_content = r.text 
soup = BeautifulSoup(html_content, 'lxml') 
anchors = soup.findAll('a') 
links = [a['href'] for a in anchors if a.has_attr('href')] 
images = [] 
def get_anchors(links): 
for a in anchors: 
    links.append(a['href']) 
return links 

raw_links = get_anchors(links) 

for element in raw_links: 
if ".jpg" in str(element) or '.png' in str(element) or '.gif' in str(element): 
    print element 
    raw_img = urllib2.urlopen("http:" + element).read() 
    DIR="C:\\Users\\deez\\Desktop\\test\\" 
    cntr = len([i for i in os.listdir(DIR) if image_type in i]) + 1 
    print cntr 
    f = open(DIR + image_type + "_"+ str(cntr)+".jpg", 'wb') 
    f.write(raw_img) 
    f.close() 
+0

4chanのは、各ポストに同じ画像への2つのリンク、画像前青の1つのリンクと画像自体の周りに一つのリンクを有しています。 – grochmal

+0

ああ、意味があります。どうすれば他のものを取り除くことができますか? –

+0

すべてのリンクをリストに追加し、重複を削除してから、リストからすべてのリンクをダウンロードすることができます。 – grochmal

答えて

0

すると、特定のリンクを取得するには、クラス名を使用し、すべてのアンカーを引っ張らないでください:

import requests 
from bs4 import BeautifulSoup 

soup = BeautifulSoup(requests.get("http://boards.4chan.org/p/").content) 

imgs = [a["href"] for a in soup.select("div.fileText a")] 

print(imgs) 

あなたはdupesを持っている理由は、各画像の同じリンクを持つ少なくとも2つのdivがあるあります:

enter image description here

関連する問題