如何使用BeautifulSoup从论坛中刮取特定图像(不包括缩略图、图标等)

2024-05-20 00:05:45 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我想获得论坛http://www.xossip.com/showthread.php?t=1384077所有图片的链接

当我查看图片(论坛帖子中的大图片)时,它们通常都有类似的内容

程序应该是什么来列出所需图像的所有URL。如果可能的话,甚至可以下载它们

我尝试了一点代码,但失败了

import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.xossip.com/showthread.php?t=1384077&page=' + str(page)
        sourcecode= requests.get(url)
        plaintext = sourcecode.text
        soup = BeautifulSoup(plaintext)
        for link in soup.findAll('img src'):
            print (link)
        page += 1
spider(1)

编辑 我想在论坛的图像,但我想避免所有的小缩略图,标志,图标等。我注意到我需要的所有图像都有这种格式<img src="http://pzy.be/i/5/17889.jpg" border="0" alt=""> 所以我需要上面格式的所有图片链接,所以我需要这个程序遍历论坛的所有页面,用src,border=0,alt优化图片,最后打印所有图片URL,比如pzy.be/i/5/452334.jpg


Tags: 图像import程序srccomhttpurlwww
1条回答
网友
1楼 · 发布于 2024-05-20 00:05:45

尝试使用tag.get('src')而不是soup.findAll('img src')

import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.xossip.com/showthread.php?t=1384077&page=' + str(page)
        sourcecode= requests.get(url)
        plaintext = sourcecode.text
        soup = BeautifulSoup(plaintext)

        for tag in soup.findAll('img'): 
            print(tag.get('src'))   # use `tag.get('src')` in this case

        page += 1
spider(1)

请查看the document了解更多详细信息


如果需要下载,还可以使用^{}下载图像的内容,并将其写入文件。下面是一个演示:

import requests
from bs4 import BeautifulSoup

def spider(max_pages):
    page = 1
    while page <= max_pages:
        url = 'http://www.xossip.com/showthread.php?t=1384077&page=' + str(page)
        sourcecode= requests.get(url)
        plaintext = sourcecode.text
        soup = BeautifulSoup(plaintext)

        for tag in soup.findAll('img'):
            link = tag.get('src')  # get the link

            # Check if the tag is in expect format
            del tag['src']
            if tag.attrs != {';': '', 'alt': '', 'border': '0'}:
                continue

            filename = link.strip('/').rsplit('/', 1)[-1]  # to get the correct file name

            image = requests.get(link).content  # use requests to get the content of the images
            with open(filename, 'wb') as f:
                f.write(image)  # write the image into a file

        page += 1
spider(1)

相关问题 更多 >