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

如何使用Beautiful Soup提取style属性中的382deg内容

解决方案

Beautiful Soup主要负责解析HTML结构并提取元素属性,要提取rotate()里的382deg,需要先拿到元素的style属性值,再用正则表达式匹配目标内容。

具体步骤:

  • 解析HTML,定位到包含目标style属性的元素,提取其style属性文本。
  • 使用正则表达式匹配rotate()括号内的内容。

代码示例:

from bs4 import BeautifulSoup
import re

# 补充完整HTML标签(根据你的实际结构调整,这里用div示例)
html = '<div style="transform-origin:50% 50%;transform:rotate(382deg)"></div>'

# 初始化Beautiful Soup解析器
soup = BeautifulSoup(html, 'html.parser')

# 定位目标元素(需根据实际HTML结构修改选择器,比如通过类名、ID等)
target_element = soup.find('div')

# 提取style属性的文本内容
style_content = target_element.get('style')

# 用正则匹配rotate括号内的度数部分
match_result = re.search(r'rotate\((.*?)\)', style_content)
if match_result:
    degree_value = match_result.group(1)
    print(degree_value)  # 输出:382deg

注意事项:

  • 如果目标元素不是div,要调整soup.find()的参数(比如soup.find('p', class_='target-class'))来精准定位。
  • 正则表达式r'rotate\((.*?)\)'采用非贪婪匹配,确保只捕获rotate()括号内的内容,避免匹配到多余字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:40:34