从<span>另一个标签中抓取文本<span>



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

<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> ...

我正在尝试分别使用 ingredient__product 和ingredient__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())

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

  • 1公斤阿尔达佩尔
  • 1 斯贾洛特

我想分隔 span 标签中的信息,所以我尝试修改我的代码,如下所示:

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

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

我做错了什么?

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

使用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等Web浏览器一起使用,以获取从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)
-
...

您感兴趣的格式化项目位于某个脚本标记中。请尝试以下操作,从该脚本标记中挖掘所需的项。

import re
import json
import requests
link = 'https://dagelijksekost.een.be/gerechten/makreel-met-aardappelen-in-de-schil-en-rode-biet'
res = requests.get(link)
json_obj = json.loads(re.findall(re.compile(r"var ingredients =(.*?);",re.DOTALL), res.text)[0])
for ingrdnt in json_obj:
print(ingrdnt['product']['name'])

您可能拥有的输出如下:

aardappel
sjalot
rode wijnazijn
rode biet
lente-ui
augurken

最新更新