beautifulsoup使用get_attr方法获取属性的值

时间:2019-03-18 20:44:06

标签: python-3.x beautifulsoup

我想打印列表中的所有项目,但不包含样式标签=以下值:"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中定义style的值吗?

2 个答案:

答案 0 :(得分:2)

只需检查标签样式中是否存在特定样式。样式不被视为multi-valued attribute,并且引号内的整个字符串是样式属性的值。使用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)

答案 1 :(得分:1)

如果您想考虑其他方法,可以使用:not选择器

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)