Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在BeautifulSoup4-Python中选择具有多个类的元素?_Python_Beautifulsoup - Fatal编程技术网

如何在BeautifulSoup4-Python中选择具有多个类的元素?

如何在BeautifulSoup4-Python中选择具有多个类的元素?,python,beautifulsoup,Python,Beautifulsoup,这里是html页面的一小部分: 1 st scenario: <p class="food_price"> <span class="food_price on_sale">$45</span> <span class="food_price">$65</span> </p> 2 nd scenario <p class="food_price"> <span class="price">

这里是html页面的一小部分:

1 st scenario:
<p class="food_price">
  <span class="food_price on_sale">$45</span>
  <span class="food_price">$65</span>
</p>

2 nd scenario
<p class="food_price">
  <span class="price">$35</span>
</p>
我得到以下错误:

Traceback (most recent call last):
  File "/home/ila/vhosts/crawler/bucky.py", line 144, in <module>
    price_sale = product_item.find('span',class_='food_price on_sale').text
AttributeError: 'NoneType' object has no attribute 'text'
回溯(最近一次呼叫最后一次):
文件“/home/ila/vhosts/crawler/bucky.py”,第144行,在
价格销售=产品项目。查找('span',class='食品销售价格')。文本
AttributeError:“非类型”对象没有属性“文本”
似乎当没有
class=“食品销售价格”
时,如果价格销售==“无”:则不会进入
。我猜,
None
似乎不是字符串

有人知道如何比较吗?

这应该会有帮助

演示:

from bs4 import BeautifulSoup
s = """<p class="food_price">
  <span class="food_price on_sale">$45</span>
  <span class="food_price">$65</span>
</p>
"""

soup = BeautifulSoup(s, "html.parser")
price_sale = soup.find('span',class_='food_price on_sale')

if price_sale:
    price_sale = price_sale.text
else:
    price_sale = -1
print(price_sale)
$45
$45