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

使用Beautiful Soup合并Tag遇TypeError,如何实现HTML标签嵌套?

问题

尝试抓取网站HTML数据并添加自定义CSS样式,使用Beautiful Soup进行数据抓取和标签转换,代码如下:

word = t.clipboard_get()

# Web Scrapping
url="https://www.vajehyab.com/?q="

response = requests.get(f"{url}{word}")
soup = BeautifulSoup(response.text, 'html.parser')
meaning = soup.find(["div", "style"], attrs={"id": "wordbox"},)


# Style
style = """<style>
    #wordbox{
        width: 500px;
    }
</style>"""

css_to_tag = BeautifulSoup(style, 'html.parser')
css = css_to_tag.find("style")

meaning += css

执行最后一行合并标签时出现错误:TypeError: unsupported operand type(s) for +=: 'Tag' and 'Tag',请问如何在Beautiful Soup中实现将一个HTML标签添加到另一个标签内部?

解决方法

Beautiful Soup的Tag对象不支持用+=直接拼接,要把一个标签添加到另一个标签内部,需使用内置的标签操作方法:

  • 添加到目标标签末尾:使用append()方法,将style标签放到wordbox标签内部的最后位置,修改最后一行代码为:
meaning.append(css)
  • 指定位置插入:如果需要把style标签插入到wordbox内部的指定位置(比如最开头),可以用insert()方法:
meaning.insert(0, css)
  • 空值判断优化:建议先判断meaning是否为None(避免网页未找到对应元素时报错):
if meaning:
    meaning.append(css)
else:
    print("未找到id为wordbox的元素")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:10:18