Python Beautifulsoup重复条目的

问题描述:

这刮从4chans摄影板的图像。问题是它擦两次相同的图像。我无法弄清楚为什么我会得到重复的照片,如果任何人都可以帮助我,那真是太棒了。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的有两个链接到同一个图像中的每个岗位,在蓝色链接的图像之前,图像本身围绕一个环节。 – grochmal

+0

啊,这是有道理的。我怎么能摆脱另一个? –

+0

您可以将所有链接添加到列表中,删除重复项,然后只从列表中下载所有链接。 – grochmal

不要拉锚每次,使用类名来获得一定的联系:

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) 

你有愚弄的原因是至少有两个div具有相同的链接为每个图像:

enter image description here