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

如何用Python爬取无class属性的网页无序列表并展示?

解决无class属性的无序列表爬取问题

你的代码无法运行的核心原因是目标无序列表没有class属性,soup.find("ul", {"class" : "class_title"})会返回None,后续遍历操作自然会报错。下面提供两种可靠的定位方式来获取目标列表:

方法一:通过标题元素定位(精准匹配页面结构)

利用页面中目标列表上方的"List"标题h2,找到它紧邻的下一个ul元素,这就是我们需要的武术列表:

import requests
from bs4 import BeautifulSoup

MA_list = "https://en.wikipedia.org/wiki/List_of_Japanese_martial_arts"

def MartialArts(): 
    url = MA_list
    resp = requests.get(url) 
      
    if resp.status_code == 200: 
        print("Successfully opened the web page") 
        print("Martial Arts :-\n") 
     
        soup = BeautifulSoup(resp.text, 'html.parser')     
        # 定位到"List"标题对应的h2元素
        list_title = soup.find("h2", string="List")
        # 获取标题下方紧邻的无序列表
        target_list = list_title.find_next_sibling("ul")
       
        # 存储武术名称的列表
        martial_arts = []
        for item in target_list.find_all("li"):
            # 提取每个列表项中的链接文本,无链接则直接取文本
            art_name = item.find("a").text if item.find("a") else item.text
            martial_arts.append(art_name)
            print(art_name)
        
        # 后续可直接使用martial_arts列表进行展示或其他操作
        # print("\n已存入列表的武术名称:", martial_arts)
    else: 
        print("Error") 
          
MartialArts()

方法二:通过内容区域筛选(适配页面结构小变化)

如果页面标题文本可能发生变动,可通过页面的内容解析区域,筛选出符合项数范围的无序列表(目标列表大约有30个项):

import requests
from bs4 import BeautifulSoup

MA_list = "https://en.wikipedia.org/wiki/List_of_Japanese_martial_arts"

def MartialArts(): 
    url = MA_list
    resp = requests.get(url) 
      
    if resp.status_code == 200: 
        print("Successfully opened the web page") 
        print("Martial Arts :-\n") 
     
        soup = BeautifulSoup(resp.text, 'html.parser')     
        # 定位到页面的内容解析区域
        content_area = soup.find("div", class_="mw-parser-output")
        target_list = None
        
        # 遍历所有ul元素,筛选项数在25-35之间的列表(匹配目标列表的规模)
        for ul in content_area.find_all("ul"):
            item_count = len(ul.find_all("li"))
            if 25 <= item_count <= 35:
                target_list = ul
                break
        
        if target_list:
            martial_arts = []
            for item in target_list.find_all("li"):
                art_name = item.find("a").text if item.find("a") else item.text
                martial_arts.append(art_name)
                print(art_name)
        else:
            print("未找到目标列表")
    else: 
        print("Error") 
          
MartialArts()

两种方法都能精准获取目标武术列表,同时将名称存入martial_arts列表,方便后续的展示或更新操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:02:16