mei*_*hys 2 html css python beautifulsoup python-2.7
我正在尝试使用Python2.7中的BeautifulSoup(bs4)包在html文档中查找以下标记:
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:408px; top:540px; width:14px; height:9px;"><span style="font-family: OEULZL+ArialMT; font-size:9px">0.00<br></span></div>
Run Code Online (Sandbox Code Playgroud)
在html文档中,还有多个其他标签几乎完全相同 - 唯一一致的区别是"left:408px"和"height:9px"属性.
我怎样才能找到这个标签BeautifulSoup?
我尝试过以下方法:
from bs4 import BeautifulSoup as bs
soup = bs("<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:408px; top:540px; width:14px; height:9px;"><span style="font-family: OEULZL+ArialMT; font-size:9px">0.00<br></span></div>", 'html.parser')
soup.find_all('div', style=('left:408px' and 'height:9px'))
soup.find_all('div', style=('left:408px') and style=('height:9px')) #doesn't like style being used twice
soup.find_all('div', {'left':'408px' and 'height':'9px'})
soup.find_all('div', {'left:408px'} and {'height:9px'})
soup.find_all('div', style={'left':'408px' and 'height':'9px'})
soup.find_all('div', style={'left:408px'} and {'height:9px'})
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
您可以检查style有left:408px和height:9px它里面:
soup.find('div', style=lambda value: value and 'left:408px' in value and 'height:9px' in value)
Run Code Online (Sandbox Code Playgroud)
要么:
import re
soup.find('div', style=re.compile(r'left:408px.*?height:9px'))
Run Code Online (Sandbox Code Playgroud)
要么:
soup.select_one('div[style*="408px"]')
Run Code Online (Sandbox Code Playgroud)
请注意,通常,样式属性用于定位元素不可靠.查看是否还有其他内容 - 检查父元素,兄弟元素,或者元素附近是否有相应的标签.
请注意,一个更合适的CSS选择器div[style*="left:408px"][style*="height:9px"],但由于有限的CSS选择器支持和这个bug,它不会按原样运行.