findall 只返回最后一个属性

findall returning only the last attribute

我搜索过类似的问题,但没有找到我需要的。

我在网络上搜索两个属性,在这种情况下 redgreenspan

from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
soup=BeautifulSoup(html,'html.parser')
nameList=soup.findAll("span",{"class":"red","class":"green"})
print(nameList)

但是我只获得了绿色属性,我尝试使用

nameList,nameList2=soup.findAll("span",{"class":"red","class":"green"})

但我收到错误 ValueError: too many values to unpack (expected 2) 有没有办法打印两个属性并将每个属性存储在一个名称列表中(不使用多个 findAll

您可以尝试使用 CSS 选择器将 span 与两个 class 名称匹配,如下所示:

nameList = soup.select("span.red, span.green")

如果您仍想使用 findAll,请尝试

nameList = soup.findAll("span",{"class":["red", "green"]})

由于您的红色和绿色是唯一的 class 属性,您可以使用 class 属性检查跨度

from urllib.request import urlopen
from bs4 import BeautifulSoup
html=urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
soup=BeautifulSoup(html,'html.parser')
nameList=soup.select("span[class]")
print(nameList)

要有单独的列表,您可以按 class 名称使用 2 个选择:

reds = soup.select('span.red')
greens = soup.select('span.green')
print(reds,greens)