【发布时间】:2019-11-09 12:04:43
【问题描述】:
我试图弄清楚css pseudo-classes 与not:() 和has:() 在以下情况下的工作方式。
以下选择器不应该打印27A-TAX DISTRICT 27A,但它会打印它:
from bs4 import BeautifulSoup
htmlelement = """
<tbody>
<tr style="">
<td><a>27A-TAX DISTRICT</a> 27A</td>
</tr>
<tr style="">
<td><strong>Parcel Number</strong> 720</td>
</tr>
</tbody>
"""
soup = BeautifulSoup(htmlelement,"lxml")
item = soup.select_one("tr:not(a)").text
print(item)
另一方面,下面的选择器应该打印I should be printed,但它会抛出AttributeError 错误。
from bs4 import BeautifulSoup
htmlelement = """
<p class="vital">I should be printed</p>
<p>I should not be printed</p>
"""
soup = BeautifulSoup(htmlelement,"lxml")
item = soup.select_one("p:has(.vital)").text
print(item)
我哪里出错了,我怎样才能让它们发挥作用?
【问题讨论】:
-
我不认为它是重复的
-
如果您认为这篇文章是重复的,那么您应该知道我的脚本行为不正确的原因@Zaraki Kenpachi。那是什么?
-
这不是重复的。用户只是询问对
:has()和:not()的操作方式存在误解。混淆是由于对:has()和:not()实际运作方式的误解,我在下面的答案中已经解决了这一点。
标签: python python-3.x beautifulsoup css-selectors