如何用BeautifulSoup过滤列表数据?过滤紫色衣物代码失效求助
问题
我想用BeautifulSoup做一个简单的网页抓取演示,制作了一份衣物列表,希望过滤掉其中的紫色款式。我写了一条if语句但完全不起作用,求帮忙。
以下是对应的HTML和Python代码:
Python代码
from bs4 import BeautifulSoup with open ('local.html', 'r') as html_file: content = html_file.read() soup = BeautifulSoup(content, 'lxml') clothingdiv = soup.find_all('div', class_ = 'clothing') for element in clothingdiv: text = element.find_all('li') if 'Purple' not in text: print(text)
HTML代码
<div class="clothing"> <li>Purple Shirt: $10</li> <li>Orange Shirt: $10</li> <li>Red Shirt: $10</li> <li>White Shirt: $10</li> <li>Purple Hoodie: $15</li> <li>Orange Hoodie: $15</li> <li>Red Hoodie: $15</li> <li>Purple Jacket: $20</li> <li>Orange Jacket: $20</li> <li>Red Jacket: $20</li> <li>White Jacket: $20</li> </div>
解决方案
你的问题出在判断逻辑上:element.find_all('li')返回的是BeautifulSoup的Tag对象列表,不是字符串。直接用'Purple' not in text判断,相当于检查字符串是否在Tag对象的列表里,这永远为True,所以所有内容都会被打印出来。
修正后的代码如下:
from bs4 import BeautifulSoup with open('local.html', 'r') as html_file: content = html_file.read() soup = BeautifulSoup(content, 'lxml') # 因为页面只有一个clothing类的div,用find()代替find_all()更高效 clothing_div = soup.find('div', class_='clothing') # 获取所有衣物项的li标签 clothing_items = clothing_div.find_all('li') # 遍历每个li标签,检查文本内容 for item in clothing_items: # 获取li的纯文本,strip=True去除多余空格 item_text = item.get_text(strip=True) if 'Purple' not in item_text: print(item_text)
关键改动点:
- 遍历单个li标签,而不是对整个li列表做判断
- 用
get_text()提取标签的纯文本内容,再检查是否包含"Purple" - 针对单个div的场景,用
find()替代find_all()减少不必要的遍历
内容的提问来源于stack exchange,提问作者Dave Goldstein
相关产品推荐
相关产品推荐

