主题闭
我有这部分代码
containers = page_soup.findAll('div',{'class' : 'product-count d-flex align-items-center'})
output = ''
for container in containers:
price = container.find('span',{'class':'lang'}).text.replace(",", "") if container.find('span',{'class':'lang'}) else ""从这个HTML页面中提取我需要的值。
<div class="product-count d-flex align-items-center">
<span class="icon-military_tech" style="color: #FFCF57; font-size: 16px"></span>
<span class="lang">bought 24 times</span>
</div>结果是买了24倍
但是对于其他站点,当HTML代码是
<div data-v-fd0de2e2=""><div data-v-fd0de2e2="" class="product-features"><!----> <div data-v-fd0de2e2=""><span data-v-fd0de2e2="" class="sold_products_count">bought 53 times</span></div></div> <!----> <!----> <div data-v-fd0de2e2="" class="product-meta"><div data-v-fd0de2e2="" class="product-sku"><strong data-v-fd0de2e2="">product code: </strong> <span data-v-fd0de2e2="">1200100045</span></div> <br data-v-fd0de2e2=""> <div data-v-fd0de2e2="" class="product-sku"><strong data-v-fd0de2e2="">weight: </strong> <span data-v-fd0de2e2="" style="direction: ltr; display: inline-block;">
0 kg
</span></div> <br data-v-fd0de2e2=""> <!----></div></div>修改后的python代码提供了空文件结果。
containers = page_soup.findAll('div',{'class' : 'product-features'})
output = ''
for container in containers:
price = container.find('span',{'class':'sold_products_count'}).text.replace(",", "") if container.find('span',{'class':'sold_products_count'}) else ""最后一个站点所需的结果是购买了53倍于
发布于 2022-07-06 21:47:00
在退出之前,代码会遍历整个containers,每次都会覆盖price,因此price的最终值是来自最后一个“容器”的值,不管它是否包含您要查找的数据。
一旦找到所需的值,就可以跳出循环,如下所示:
containers = page_soup.findAll('div',{'class' : 'product-features'})
output = ''
for container in containers:
price = container.find('span',{'class':'sold_products_count'}).text.replace(",", "") if container.find('span',{'class':'sold_products_count'}) else ""
if price:
break
print(price)https://stackoverflow.com/questions/72890092
复制相似问题