我是第一次練習 BeautifulSoup 和 HTML 請求。該程式的目標是加載一個網頁和它的 HTML,然后搜索網頁(在這種情況下是一個食譜,以獲取它的成分的子字串)。我已經設法讓它使用以下代碼:
url = "https://www.bbcgoodfood.com/recipes/healthy-tikka-masala"
result = requests.get(url)
myHTML = result.text
index1 = myHTML.find("recipeIngredient")
index2 = myHTML.find("recipeInstructions")
ingredients = myHTML[index1:index2]
但是當我在這里嘗試使用 BeautifulSoup 時:
url = "https://www.bbcgoodfood.com/recipes/healthy-tikka-masala"
result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")
ingredients = doc.find(text = "recipeIngredient")
print(ingredients)
我知道上面的代碼(即使我可以讓它作業)會產生一個不同的輸出只是 [“recipeIngredient”] 但這就是我現在關注的所有內容,同時我掌握了 BS。相反,上面的代碼只輸出 None。我在終端上列印了“doc”,它只會輸出看起來是 HTML 的后半部分的內容(或者至少:不是全部)。然而,文本檔案確實包含所有 HTML,所以我認為這就是問題所在,但我不知道如何解決它。
謝謝你。
uj5u.com熱心網友回復:
你需要使用:
class_="recipe__ingredients"
例如:
import requests
from bs4 import BeautifulSoup
url = "https://www.bbcgoodfood.com/recipes/healthy-tikka-masala"
doc = (
BeautifulSoup(requests.get(url).text, "html.parser")
.find(class_="recipe__ingredients")
)
ingredients = "\n".join(
ingredient.getText() for ingredient in doc.find_all("li")
)
print(ingredients)
輸出:
1 large onion , chopped
4 large garlic cloves
thumb-sized piece of ginger
2 tbsp rapeseed oil
4 small skinless chicken breasts, cut into chunks
2 tbsp tikka spice powder
1 tsp cayenne pepper
400g can chopped tomatoes
40g ground almonds
200g spinach
3 tbsp fat-free natural yogurt
? small bunch of coriander , chopped
brown basmati rice , to serve
uj5u.com熱心網友回復:
它輸出None是因為它正在尋找 html 標簽中的內容在哪里'recipeIngredient',而 whci 不存在(html 內容中沒有文本。該字串是 html 標簽的屬性)。
您實際上試圖通過 bs4 獲得的是找到您想要的資料/內容的特定標簽和/或屬性。例如,@baduker 指出,html 中的成分在帶有 class 屬性 =“recipe__ingredients”的標簽內。
您在第一個代碼塊中提取的字串'recipeIngredient'實際上來自<script>html 中的標記,該標記具有 json 格式的成分。
from bs4 import BeautifulSoup
import requests
import json
url = "https://www.bbcgoodfood.com/recipes/healthy-tikka-masala"
result = requests.get(url)
doc = BeautifulSoup(result.text, "html.parser")
ingredients = doc.find('script', {'type':'application/ld json'}).text
jsonData = json.loads(ingredients)
print(jsonData['recipeIngredient'])

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/519393.html
