【问题标题】:How to exclude child in Python如何在 Python 中排除孩子
【发布时间】:2018-11-06 16:19:34
【问题描述】:

我用python写了一个脚本来获取网站上的产品价格,但是我发现了一个问题。有时有些产品在打折,因为它们有 2 个价格(原始价格和实际价格)。我的脚本得到了所有这些,但我不想要销售前的价格。我怎样才能排除它们?有可能吗?

源代码示例:

正常价格

 <div class="result-actions"
   <span> ==$0
     $ 1,98
   </span>

特价

 <div class="result-actions">
   <span>
     <small class="price-before"> ==$0
       $ 56,70
     </small>
     <span class="price-now">
       $ 39,60
     </span>
   </span>
                                            

我的脚本

import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup

site = input()
html = urlopen(site)
bs = BeautifulSoup(html, 'html.parser')
pricesList = bs.findAll('div',{'class':'result-actions'})
csvFile = open('Prices.csv', 'wt+')
writer = csv.writer(csvFile)


try:
  for prices in pricesList:
    print(clean_up_text(prices.get_text()))
    csvPrice = []
    csvPrice.append(clean_up_text(prices.get_text().strip()))
    writer.writerow(csvPrice)                  
finally:
  csvFile.close()

请帮帮我!

更新

我试图包含一个功能来排除旧价格,但它似乎也不起作用。

def excluir_precos_antigos(element):
  element = driver.find_element_by_class_name('price-before')
    driver.execute_script("""var element = 
    arguments[0];element.parentNode.removeChild(element);""", element)

【问题讨论】:

    标签: python csv beautifulsoup


    【解决方案1】:

    您可以简单地找到存储售价的span标签:

    d = """
    <div class="result-actions">
     <span>
      <small class="price-before"> ==$0
       $ 56,70
      </small>
      <span class="price-now">
       $ 39,60
      </span>
    </span>
    </div>
    """
    

    from bs4 import BeautifulSoup as soup
    result = soup(d, 'html.parser').find('span', {'class':'price-now'}).text
    

    输出:

    '\n   $ 39,60\n  '
    

    如果页面上有多个result-actionsdivs,可以使用find_all

    final_results = [i.find('span', {'class':'price-now'}).text for i in soup(d, 'html.parser').find_all('div', {'class':'result-actions'})]
    

    它给出了页面上的所有销售价格:

    ['\n   $ 39,60\n  ']
    

    【讨论】:

    • 您好 Ajax,感谢您的帮助!但我认为它不会像我希望的那样工作,因为未出售的产品不会出现在输出中。我可以设置条件不包括“之前的价格”吗?
    猜你喜欢
    • 2018-07-16
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 2014-11-21
    • 2011-11-08
    • 2013-01-08
    • 1970-01-01
    • 2011-01-28
    相关资源
    最近更新 更多