首页 > 解决方案 > 尝试 If Elif Else 语句,只返回两个值

问题描述

我正在尝试编写 If Elif Else 语句,我可能会错误地处理这个问题。我已经用 Pandas 构建了一个 DataFrame,我试图做的是表示列中 3 个状态中的 1 个。特殊订单,准备发货,只是空白或连字符。我已经尝试了几种不同的方法,但似乎无法让它发挥作用。我试图做的是,如果某物的价格为 0.00 美元,则返回第三个状态,即空白或连字符。目前,无论我做什么,我都会收到特殊订单或准备发货。

这是来自网站的代码,我很抱歉它是如此混乱,它只是从它们格式化的方式。

   <table cellspacing="0" class="item width-100" summary="Wish list">
            <tr>
              <td><input type="checkbox" name="wish_products" value="583454" class="wish_check  available " /></td>
              <td class="image">
                <a title="A Walk Through Hell Complete Hc" href="/a-walk-through-hell-complete-hc.html">
                                      <img src="https://www.cheapgraphicnovels.com/images/P/A%20WALK%20THROUGH%20HELL%20COMPLETE%20HC.jpg" width="97" alt="A WALK THROUGH HELL COMPLETE HC" title="A WALK THROUGH HELL COMPLETE HC" />                                  </a>
              </td>
              <td class="details">

                                <a title="A Walk Through Hell Complete Hc" href="/a-walk-through-hell-complete-hc.html" class="product-title">A WALK THROUGH HELL COMPLETE HC</a>

                <div class="descr"><p>
    <span style="font-size:14px;">Garth Ennis&#39; Complete Masterpiece of Terror in One Unrelenting Hardcover! So these two FBI agents walk into a warehouse... Special Agents Shaw and McGregor handle the routine cases nowadays, which is just the way Shaw likes it.</span></p>
<p>
    &nbsp;</p>
<p>
    <strong><span style="font-size:14px;">ESTIMATED ARRIVAL: TBA</span></strong></p>
</div>
        
                                  <span class="product-price-text">
                    <span class="currency">$29.99</span> x <input type="text" size="3" name="quantity" id="qty_583454" value="1" /> = 
                  </span>
                  <span class="price">
                    <span class="currency">$29.99</span>
                  </span>
                  <span class="market-price">
                    
                  </span>
 
              </td>
            </tr>
            <tr><td>&nbsp;</td>
              <td class="buttons-row">

    <a class="simple-button simple-delete-button" href="cart.php?mode=wldelete&amp;wlitem=583454&amp;eventid=" title="Delete item"><span>Delete item</span></a>
    
              </td>
              <td class="buttons-row">

  <button class="button light-button" type="submit" title="Update">
  <span class="button-right"><span class="button-left">Update</span></span>
  </button>

                  <div class="button-separator"></div>
                            
<div style="float:left"> 
        <a href="javascript://" onclick="javascript: self.location = 'cart.php?mode=wl2cart&amp;wlitem=583454&amp;amount='+$('#qty_583454').val()"><img src="/skin/common_files/images/add_cart_btn_hov.png" border="0" alt="" /></a>
    </div>
                                     
              </td>
            </tr>

                                     <tr>
              <td>&nbsp;</td>
                <td colspan="2">                 
<div class="ordernow">This title is available by Special Order only.  Please read our <a href="/covid-19.html">COVID-19 Update</a> prior to ordering.</div>
                </td>
              </tr>

                          <tr>
                <td>&nbsp;</td>
                <td>
                                  </td>
              </tr>
            
          </table>
          
          <table cellspacing="0" class="item width-100" summary="Wish list">
            <tr>
              <td><input type="checkbox" name="wish_products" value="584040" class="wish_check " /></td>
              <td class="image">
                <a title="Abe Sapien Dark And Terrible Vol 01 Hc" href="/abe-sapien-dark-and-terrible-vol-01-hc.html">
                                      <img src="https://www.cheapgraphicnovels.com/images/P/ABE%20SAPIEN%20DARK%20%26%20TERRIBLE%20HC%20VOL%2001.jpg" width="98" alt="ABE SAPIEN DARK AND TERRIBLE VOL 01 HC " title="ABE SAPIEN DARK AND TERRIBLE VOL 01 HC " />                                  </a>
              </td>
              <td class="details">

                                <a title="Abe Sapien Dark And Terrible Vol 01 Hc" href="/abe-sapien-dark-and-terrible-vol-01-hc.html" class="product-title">ABE SAPIEN DARK AND TERRIBLE VOL 01 HC </a>

                <div class="descr"><p>
    <span style="font-size:14px;">On the run from the BPRD, a newly mutated Abe Sapien-more inhuman than before-travels across a United States transformed and overrun by monsters. Abe&#39;s search for the truth about himself-or his race away from his fate-mirrors the quest of an ancient necromancer to seize control of a world literally going to hell. </span></p>
</div>
       
                                  <span class="product-price-text">
                    <span class="currency">$24.49</span> x <input type="text" size="3" name="quantity" id="qty_584040" value="0" /> = 
                  </span>
                  <span class="price">
                    <span class="currency">$0.00</span>
                  </span>
                  <span class="market-price">
                    
                  </span>
                
                                  <strong>Out of stock</strong>
                
              </td>
            </tr>
            <tr><td>&nbsp;</td>
              <td class="buttons-row">

    <a class="simple-button simple-delete-button" href="cart.php?mode=wldelete&amp;wlitem=584040&amp;eventid=" title="Delete item"><span>Delete item</span></a>
   
              </td>
              <td class="buttons-row">

  <button class="button light-button" type="submit" title="Update">
  <span class="button-right"><span class="button-left">Update</span></span>
  </button>

                  <div class="button-separator"></div>
                
                
              </td>
            </tr>
    
                          <tr>
                <td>&nbsp;</td>
                <td>
                                  </td>
              </tr>
            
          </table>

到目前为止,这是我的代码,它起作用了,我只是无法让 If、Elif、Else 部分在特殊命令下工作。

titles = []
links = []
price = []
special_order = []
addtocart = []

soup = BeautifulSoup(driver.page_source, "html.parser")
cgn_items = soup.find_all('table', class_='item width-100')
sleep(randint(2,10))

for container in cgn_items:

    #name
    name = container.find('a', class_='product-title').text.strip()
    titles.append(name)
    
    #link
    link = container.find('td', attrs={'class' : 'details'})
    for div in link:
        linking = container.find('a')['href']
        link = "https://www.cheapgraphicnovels.com" + linking
    links.append(link)
    
    #price
    pricing = container.find('span', class_='price')
    if pricing:
        price.append(pricing.text.strip())
    else:
        price.append('-')
    
    #special order
    special = container.find('div', class_='ordernow')
    if special:
        special_order.append('Special Order')
    else:
        special_order.append('Ready to Ship')
    
    #addtocart
    cart = container.find('img', {"src" : "/skin/common_files/images/add_cart_btn_hov.png"})
    if cart:
        addtocart.append('In Stock')
    else:
        addtocart.append('Out of Stock')

cgn_wishlist = pd.DataFrame({
'book': titles,
'link': links,
'price': price,
'special_order': special_order,
'cart': addtocart
})

cgn_wishlist.to_csv('cgn_wishlist.csv', index=False)

目前,如果它找到它知道分配特殊订单的 ordernow 类,它就会起作用,对于其他一切它只是准备好发货。但我想要的是任何价格为 0.00 美元的商品为空白或“-”,其余商品(由于价格高于 0.00 美元而被视为库存商品)将获得“准备发货”

对此的任何帮助将不胜感激,谢谢!

标签: pythonpython-3.xweb-scrapingbeautifulsoup

解决方案


据我所知,您只需要elif在“特殊订单”代码中添加一个附加项,如下所示:

#special order
special = container.find('div', class_='ordernow')
if special:
    special_order.append('Special Order')
elif price[-1] in ['-', '$0.00']:
    special_order.append('-')
else:
    special_order.append('Ready to Ship')

这将检查价格是否为-or$0.00然后添加-

这应该为您提供数据框,例如:

                    book                   link   price  special_order          cart
0  A WALK THROUGH HEL...  https://www.cheapg...  $29.99  Special Order      In Stock
1  ABE SAPIEN DARK AN...  https://www.cheapg...   $0.00              -  Out of Stock

price是您的价格列表,列表中的最后一个条目是price[-1],负值从列表末尾开始(price[0]将是第一个值)。Python 的in运算符检查一个值是否与列表中的任何值匹配。由于您有两个测试,因此可以将它们制成要测试的值列表,例如['-', '$0.00']


推荐阅读