如何使用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
相关产品推荐
相关产品推荐

