使用BeautifulSoup查找具有两种特定样式的标签

发布于 2021-01-29 17:02:07

我正在尝试使用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>

在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'})

有任何想法吗?

关注者
0
被浏览
42
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以检查里面是否styleleft:408pxheight:9px

    soup.find('div', style=lambda value: value and 'left:408px' in value and 'height:9px' in value)
    

    要么:

    import re
    soup.find('div', style=re.compile(r'left:408px.*?height:9px'))
    

    要么:

    soup.select_one('div[style*="408px"]')
    

    请注意,通常, 样式属性对于定位元素不可靠 。看看是否还有其他内容-检查父级,同级元素,或者元素附近是否有相应的标签。

    请注意,一个更合适的CSS选择器将是div[style*="left:408px"][style*="height:9px"],但是由于CSS选择器的支持有限以及此错误,它无法按原样工作。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看