输入 HTML:
<div style="display: flex">
<div class="half" style="font-size: 0.8em;width: 33%;"> apple </div>
<div class="half" style="font-size: 0.8em;text-align: center;width: 28%;"> peach </div>
<div class="half" style="font-size: 0.8em;text-align: right;width: 33%;" title="nofruit"> cucumber </div>
</div>
所需的输出: all div
正好在下面的元素<div style="display: flex">
.
我正在尝试找到家长div
with a CSS 选择器:
div[style="display: flex"]
这会引发错误:
>>> soup.select('div[style="display: flex"]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/user/.virtualenvs/so/lib/python2.7/site-packages/bs4/element.py", line 1400, in select
'Only the following pseudo-classes are implemented: nth-of-type.')
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
看起来像BeautifulSoup
尝试将冒号解释为伪类语法。
我尝试遵循以下建议的建议处理 CSS 选择器中元素 ID 中的冒号,但它仍然抛出错误:
>>> soup.select('div[style="display\: flex"]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/user/.virtualenvs/so/lib/python2.7/site-packages/bs4/element.py", line 1400, in select
'Only the following pseudo-classes are implemented: nth-of-type.')
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
>>> soup.select('div[style="display\3A flex"]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/user/.virtualenvs/so/lib/python2.7/site-packages/bs4/element.py", line 1426, in select
'Unsupported or invalid CSS selector: "%s"' % token)
ValueError: Unsupported or invalid CSS selector: "div[style="displayA"
问题:
在属性值中使用/转义冒号的正确方法是什么BeautifulSoup
CSS 选择器?
请注意,我可以通过部分属性匹配来解决它:
soup.select("div[style$=flex]")
或者,用一个find_all():
soup.find_all("div", style="display: flex")
另请注意,我了解使用style
定位元素远不是一个好的定位技术,但问题本身是通用的,并且提供的 HTML 只是一个示例。