无法访问从json响应派生的单个配方的内部页面

2024-06-16 08:54:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着从一个webpage中找出不同的食谱。到目前为止,我所写的内容可以解析所有配方名称。然而,我找不到任何方法来访问单个配方链接。以下是每个容器的外观,其中没有可用的slug,因此我找不到任何关于如何访问不同配方的内部页面的线索:

{'id': 748,
 'img': 'https://cdn-uploads.mealime.com/uploads/recipe/thumbnail/41/thumbnail_708f7645-6cb4-4089-8e18-95f5b97cbbcf.jpg',
 'name': 'Apple Quinoa Salad with Celery, Almonds & Dried Cranberries',
 'recipeId': 41,
 'restrictions': [6],
 'types': [1, 3, 2, 4]}

如果我没有错的话,这是https://www.mealime.com/_next/data/kSmAjTn7MJl4zVPNE6MeR/recipes/greek-turkey-meatball-pita-wraps-veggies-olives-feta-sauce/14887.json一个单独的配方链接应该是什么样子的,它会引导到内部页面

我试过:

import requests
from pprint import pprint

link = 'https://www.mealime.com/_next/data/kSmAjTn7MJl4zVPNE6MeR/recipes.json'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
    res = s.get(link)
    for item in res.json()['pageProps']['reducedVariants']:
        pprint(item)

How can I access to the inner page of individual recipe derived from json response?


Tags: httpscomjsondata链接wwwwith配方
1条回答
网友
1楼 · 发布于 2024-06-16 08:54:13

在这里,我已经为一个您可以用于所有的应用做了准备,但是name可以包含必须删除的不必要的单词,然后我们可以再次发出请求,您可以获得所需的输出:

import requests
from pprint import pprint
import re

main_url="https://www.mealime.com/_next/data/kSmAjTn7MJl4zVPNE6MeR/recipes"
json=".json"

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'

    res = s.get(main_url+json)      
    main_data=res.json()

    for i in range(len(main_data['pageProps']['reducedVariants'])):
        if main_data['pageProps']['reducedVariants'][i]['id']==14887:
            name=main_data['pageProps']['reducedVariants'][i]['name'].replace("with","")
            id_=main_data['pageProps']['reducedVariants'][i]['id']
            name="-".join(re.findall("[a-zA-Z]+", name.lower()))
            detail_res=requests.get(main_url+"/"+name+"/"+str(id_)+json)
            print(detail_res.json()['pageProps']['publishedRecipe']['line_items'])

输出:

[{'id': 258630, 'quantity': '1 (4 oz) pkg', 'ingredient_name': 'crumbled feta cheese'}, {'id': 258637, 'quantity': '2', 'ingredient_name': 'eggs'}, {'id': 258641, 'quantity': '1', 'ingredient_name': 'English cucumber'}, {'id': 258647, 'quantity': '1 small bunch', 'ingredient_name': 'fresh dill'}, {'id': 258629, 'quantity': '4 cloves', 'ingredient_name': 'garlic'},....

相关问题 更多 >