You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

网页图片Title爬取问题:如何筛选目标值并整合到现有爬虫脚本

爬虫问题解决:获取指定布局图片title并整合输出

问题说明

已完成爬虫脚本,可获取网页中的队名、分数和竞技场信息,但需要补充获取3×2布局的图片title(这些图片无class属性)。直接遍历所有img标签会返回大量None值,需将每队对应的3个图片title整合到现有输出中。

现有代码

import requests
from bs4 import BeautifulSoup


def analyze(i):
    url = f"https://ktarena.com/fr/207-dofus-world-cup/match/{i}/1"
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")

    names = [a.text for a in soup.select(".name a")]
    points = [p.text for p in soup.select(".result .points")]
    arena = soup.find("span", attrs=('name')).text
    
    print(*zip(names, points,),arena)
    

for i in range(46270, 46273):  
    analyze(i)

解决方案

  1. 精准定位图片容器:跳过页面所有img标签的全局遍历,直接定位每个队伍专属的图片父容器(页面中每队3张图都在.characters容器内),避免抓取无关图片。
  2. 提取有效图片title:针对每个队伍的容器,提取其中img标签的title属性,自动过滤无title的无效标签。
  3. 整合数据输出:将每队的队名、分数、3个图片title与竞技场信息打包后输出。

修改后的完整代码

import requests
from bs4 import BeautifulSoup


def analyze(i):
    url = f"https://ktarena.com/fr/207-dofus-world-cup/match/{i}/1"
    page = requests.get(url)
    soup = BeautifulSoup(page.content, "html.parser")

    # 获取队名、分数、竞技场信息
    names = [a.text.strip() for a in soup.select(".name a")]
    points = [p.text.strip() for p in soup.select(".result .points")]
    arena = soup.find("span", attrs={'name'}).text.strip()
    
    # 获取每队对应的3个图片title
    team_characters = []
    # 定位每个队伍的容器
    teams = soup.select(".team")
    for team in teams:
        # 提取当前队伍下所有图片的title(过滤空值)
        char_titles = [img.get('title').strip() for img in team.select(".characters img") if img.get('title')]
        team_characters.append(char_titles)
    
    # 整合并输出数据
    for name, point, chars in zip(names, points, team_characters):
        print(f"队名: {name}, 分数: {point}, 角色: {chars}")
    print(f"竞技场: {arena}\n")
    

for i in range(46270, 46273):  
    analyze(i)

内容的提问来源于stack exchange,提问作者Joost

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:40:37