我想从列表“ all_size”中排除属性为“ disabled”的元素“ input”。
html:
<div class="container">
<input id="skuAndSize__22356651:7" disabled="" />
<input id="skuAndSize__22356650:7.5" />
</div>
我当前的python代码:
soup = bs(response.text,"html.parser")
div = soup.find("div",{"class":"container"})
all_sizes = div.find_all("input")
size_in_stock = []
for size in all_sizes:
size_id = size["id"]
size_in_stock.append(size_id.split("__")[1])
感谢每个答案
答案 0 :(得分:1)
您可以简单地添加一个条件:
size_in_stock = []
for size in all_sizes:
size_id = size["id"]
if 'disabled' not in size.attrs:
size_in_stock.append(size_id.split("__")[1])
整个列表理解:
size_in_stock = [size["id"].split("__")[1] for size in all_sizes
if 'disabled' not in size.attrs]
答案 1 :(得分:0)
深空击败了我,所以接受他的回答。但是,作为替代方案,我检查了"disabled"
是否存在,如果存在,请跳过并继续到下一项:
from bs4 import BeautifulSoup as bs
html = '''<div class="container">
<input id="skuAndSize__22356651:7" disabled="" />
<input id="skuAndSize__22356650:7.5" />
</div>'''
soup = bs(html,"html.parser")
div = soup.find("div",{"class":"container"})
all_sizes = div.find_all("input")
size_in_stock = []
for size in all_sizes:
size_id = size["id"]
if 'disabled' in size.attrs:
continue
size_in_stock.append(size_id.split("__")[1])