Skip to main content
 首页 » 编程设计

python之BeautifulSoup 在 Python 中抓取 itemprop ="name"

2025年05月04日22lonelyxmas

我有一些 python 3.5 代码,我想用它来抓取网页的一部分,但不是打印“又厚又耐嚼的花生酱巧克力片”,而是打印“无”。你知道为什么吗?谢谢。

import requests, bs4 
import tkinter as tk 
from tkinter import * 
import pymysql 
import pymysql.cursors 
 
res = requests.get("http://www.foodnetwork.co.uk/article/traybake-recipes/thick-and-chewy-peanut-butter-chocolate-chip-bars/list-page-2.html") 
res.raise_for_status() 
recipeSoup = bs4.BeautifulSoup(res.text, "html.parser") 
type(recipeSoup) 
instructions = recipeSoup.find("div", itemprop="name") 
try: 
    method = str.replace(instructions.get_text(strip=True),". ",".") 
    method = str.replace(method, ". ", ".") 
    method = (str.replace(method, ".",".\n")) 
except AttributeError: 
    print(instructions) 

Link to scraped page

请您参考如下方法:

将 instructions = recipeSoup.find("div", itemprop="name") 更改为 instructions = recipeSoup.find("span", itemprop="name") 获取食谱标题。

有关说明,您必须使用 itemprop=ingredients 搜索 li 标签。