首页 > 解决方案 > 如何从beautifulsoup中的span标签中获取字符串

问题描述

我在将字符串从 beautifulsoup 中的 span 标签中取出时遇到问题。我尝试使用 text 属性,但这给了我一个 AttributeError: NoneTypeobject has no attribute text

source = requests.get("https://www.k-ruoka.fi/kauppa/tuotehaku").text

soup = BeautifulSoup(source, "lxml")


product = soup.find("ul", class_="product-grid")


for listt in product.find_all("li"):
    kg = listt.find("span", class_="reference").text
    print(kg)

上面的代码给出了 AttributeError。如果我不使用 .text 那么它给了我这个:

<span class="reference">1,58<span class="slash">/</span>kg</span>

但我只想要它的“1,58”和“kg”。

标签: pythonhtmlbeautifulsoup

解决方案


您的代码有效,您只需要NoneType在 for 循环中进行检查:

for listt in product.find_all("li"):
    kg = listt.find("span", class_="reference")
    if kg:
        print(kg.text)

推荐阅读