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

Python3.10+BeautifulSoup4.9.0兄弟节点报错求助:'NoneType'无'tr'属性

问题分析与解决

核心错误点

  • 标签匹配错误:你写的bs.find('title', {'id':'giftList'})是找带giftList id的<title>标签,但目标页面里这个id属于<table>标签,所以这个查找返回None,再调用.tr自然就报'NoneType' object has no attribute 'tr'的错。
  • 模块拼写错误:代码里from surllib.request import urlopen多了个s,正确模块名是urllib。

修正后的完整代码

from urllib.request import urlopen
from bs4 import BeautifulSoup
from urllib.error import HTTPError
from urllib.error import URLError
import re

# 处理表格兄弟节点的部分
try:
    html2 = urlopen('http://www.pythonscraping.com/pages/page3.html')
    bs = BeautifulSoup(html2, 'html.parser')
    # 正确找到id为giftList的表格
    target_table = bs.find('table', {'id':'giftList'})
    if target_table:
        # 遍历表格第一行的所有后续兄弟节点
        for sibling in target_table.tr.next_siblings:
            print(sibling)
    print('siblings')
except (HTTPError, URLError) as e:
    print(f"网络请求出错: {e}")

# 处理图片关联文本的部分
try:
    html3 = urlopen('http://www.pythonscraping.com/pages/page3.html')
    bs2 = BeautifulSoup(html3, 'html.parser')
    img_node = bs2.find('img', {'src':'../img/gifts/img1.jpg'})
    # 逐层判断节点是否存在,避免报错
    if img_node and img_node.parent and img_node.parent.previous_sibling:
        print(img_node.parent.previous_sibling.get_text())
    print('sibling image')
except (HTTPError, URLError) as e:
    print(f"网络请求出错: {e}")

额外说明

  • next_siblings会返回当前节点之后的所有同级节点,包括换行符这类空白节点,所以打印时会出现空行,属于正常情况。
  • 加了异常处理是为了应对网络请求失败的情况,让程序不会直接崩溃。
  • 每次调用节点属性前先判断是否为None,能有效避免类似的属性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:30:50