BeautifulSoup使用GET_ATTR方法获得属性的值



我想打印列表中的所有项目,但不包含样式标签=以下值: "text-align: center"

test = soup.find_all("p")
for x in test:
    if not x.has_attr('style'):
        print(x)

本质上,将我的所有项目返回列表中的所有项目,其中样式不等于:"text-align: center"。可能只是这里的一个小错误,但是是否可以在has_attr中定义样式的值?

只需检查标签样式中是否存在特定样式。样式不被视为多值属性,并且引号内部的整个字符串是样式属性的值。使用x.get("style",'')代替x['style']也处理没有样式属性的情况并避免KeyError

for x in test:
    if 'text-align: center' not in x.get("style",''):
        print(x)

您也可以使用列表理解来跳过几行。

test=[x for x in soup.find_all("p") if 'text-align: center' not in x.get("style",'')]
print(test)

如果要考虑一种不同的方法,则可以使用:不选择

from bs4 import BeautifulSoup as bs
html = '''
<html>
<head>
<title>Try jsoup</title>
</head>
<body>
<p style="color:green">This is the chosen paragraph.</p>
<p style="text-align: center">This is another paragraph.</p>
</body>
</html>
'''
soup = bs(html, 'lxml')
items = [item.text for item in soup.select('p:not([style="text-align: center"])')]
print(items)

最新更新