我第一次尝试使用beautifulsoup而没有得到ideao n 如何抓取下面的代码并获取o / p,如循环中获取更多项目
2杯水
<ul class="list-unstyled">
<li itemprop="ingredients">
1 cup <span class="ingredient_name">Rice flour</span>
</li>
<li itemprop="ingredients">
2 cups <span class="ingredient_name">Water</span>
</li>
</ul>
但这只取得第一项
for ingred in soup.find('ul', attrs={'class':'list-unstyled'}) :
答案 0 :(得分:0)
找到所有li
标记并循环显示它们。使用get_text()
获取文本。
from bs4 import BeautifulSoup
html = """<ul class="list-unstyled">
<li itemprop="ingredients">
1 cup <span class="ingredient_name">Rice flour</span>
</li>
<li itemprop="ingredients">
2 cups <span class="ingredient_name">Water</span>
</li>
</ul>"""
soup = BeautifulSoup(html, "lxml")
for li in soup.find_all("li", {"itemprop": "ingredients"}):
print(li.get_text())
# if you need the span too
span = li.find("span")
要了解详情,请阅读official documentation