【问题标题】:Python Beautifulsoup Duplicate entry'sPython Beautifulsoup 重复条目
【发布时间】:2016-10-13 08:16:40
【问题描述】:

这会从 4chans 摄影板上抓取图像。问题是它会刮两次相同的图像。我不知道为什么我会收到重复的照片,如果有人可以帮助我,那就太棒了。

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()

【问题讨论】:

  • 4chan 在每篇文章中都有两个指向同一张图片的链接,一个在图片之前的蓝色链接和一个围绕图片本身的链接。
  • 嗯,有道理。我怎样才能摆脱另一个?
  • 您可以将所有链接添加到列表中,删除重复项,然后才能从列表中下载所有链接。
  • 有人能用一些代码指出我正确的方向吗?我很困惑如何做到这一点。

标签: python image beautifulsoup duplicates screen-scraping


【解决方案1】:

不要拉每个锚点,使用类名获取某些链接:

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 具有相同的链接:

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 2018-09-06
    • 2021-08-02
    • 2011-12-02
    • 2015-07-23
    • 2011-11-05
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多