首页 > 解决方案 > 从另一个标签中抓取文本

问题描述

编辑:我注意到我混淆了一个脚本的代码和另一个脚本的输出。这是具有正确输出的正确代码

<div class="ingredient-list single-column">
    <div class="ingredient-list__part">
        <ul aria-labelledby="ingredients-title">
            <li>
                <span class="ingredient">
                    <span class="ingredient__product">aardappel (vastkokend)</span>
                    <span class="ingredient__unit">1 kg</span>
                </span>
            </li>
            <li>
                <span class="ingredient">
                    <span class="ingredient__product">sjalot</span>
                    <span class="ingredient__unit">1</span></span>
            </li>
            <li> ...
                

我正在尝试分别使用成分__product 和成分__unit 提取跨度内的信息。

我写的代码如下:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = "https://dagelijksekost.een.be/gerechten/makreel-met-aardappelen-in-de-schil-en-rode-biet"


#open connectie en pagina pakken
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#html parsen
page_soup = soup(page_html, "html.parser")


ingredients = page_soup.find("ul",{"aria-labelledby":"ingredients-title"})

ingredient = ingredients.findAll('li')

for i in range(len(ingredient)):
    print(ingredient[i].text.strip())

这是我的第一次尝试,并返回给我这个输出:

我想分隔跨度标记中的信息,所以我尝试修改我的代码如下:

ingredients = page_soup.find_all("span", {"class": "ingredient"})

print(ingredients)

这只会打印一个空列表。似乎我无法“访问”跨度标签之间的信息

我究竟做错了什么?

如果我已经解决了这一步,下一步就是在这个网站上循环浏览多个食谱。任何关于如何在 gerechten/ 之后的部分是可变的 URL 中循环的提示也是受欢迎的。

标签: pythonhtmlweb-scrapingbeautifulsoup

解决方案


用于find_all获取所有<span>标签,class="ingredient"然后循环遍历结果,然后解析数据,如下面的代码:

ingredients = page_soup.find_all("span", {"class": "ingredient"})
for ingredient in ingredients:
    print("ingredient product: ", ingredient.find(class_='ingredient__product').text)
    print("ingredient unit: ", ingredient.find(class_='ingredient__unit').text)
    print("-")

编辑: 从 JS 中的成分变量中解析数据,尽管我建议使用 Selenium 和像 PhantomJS 这样的网络浏览器来获取从 html 代码中的 javascript 中提取的数据:

import json
import re

load = json.loads(re.findall(r"var ingredients = (.*?);", str(page_soup))[0])

for i in load:
    if i['unit'] != None:
        print("unit:", i["amount"], i["unit"]["name"])
    else:
        print("unit:", i["amount"])
    print("product:", i["product"]["name"], i["append"])
    print("-")

输出:

unit: 1 kg
product: aardappel (vastkokend)
-
unit: 1
product: sjalot
-
unit: 0
product: rode wijnazijn
-
unit: 4
product: rode biet (gekookt)
-
...

推荐阅读