Skip to main content
 首页 » 编程设计

python之如何将列表中的空项更改为 N/a 值

2024年11月24日15rubylouvre

我的代码有问题。我正在使用 BeautifulSoup 抓取网页,我正在寻找表格中的所有内容以将它们放入列表中,但问题是当我找不到图像标签时,我需要我的值“N/a”列表。现在列表元素是空的。

这是我的代码:

cards = [] 
 
for row in TR_HP1_3[0:11]: 
       cards.append([image.get('title') for image in row.find_all('img')]) 
 
print(cards) 
 
for x in cards: 
     cards_corrected = [x if x != None else "N/a" for x in cards] 
 
print(cards_corrected) 

这给了我以下输出:

[[], [], [], ['geelrode kaart'], [], [], [], [], [], [], []] 
[[], [], [], ['geelrode kaart'], [], [], [], [], [], [], []] 

如何将这些空值更改为 N/a?

请您参考如下方法:

改变

cards.append([image.get('title') for image in row.find_all('img')]) 

与:

cards.append([image.get('title') if image.get('title') else "N/a"  
              for image in row.find_all('img')])