我正在嘗試使用 beautifulsoup 從 html 檔案中提取字典條目的“含義”部分,但這給我帶來了一些麻煩。以下是我迄今為止嘗試過的總結:
- 我右鍵單擊下面的字典條目頁面并將網頁作為“aufmachen.html”保存到我的 Python 目錄中
https://www.duden.de/rechtschreibung/aufmachen
- 在此網頁的源代碼中,我嘗試提取的部分從第 1042 行開始,運算式為
- 我在下面撰寫了代碼,但標簽和 Bedeutungen 都不包含任何搜索結果。
import requests
import pandas as pd
import urllib.request
from bs4 import BeautifulSoup
with open("aufmachen.html",encoding="utf8") as f:
doc = BeautifulSoup(f,"html.parser")
tags = doc.body.findAll(text = '<div id="bedeutungen">')
print(tags)
Bedeutungen = doc.body.findAll("div", {"id": "bedeutungen"})
print(Bedeutungen)
你能幫我解決這個問題嗎?
提前感謝您的時間。
uj5u.com熱心網友回復:
您的代碼中的主要錯誤是您向 BS 發送一個檔案,而不是一個字串。呼叫.read()您的檔案以獲取字串。
with open("aufmachen.html", "r",encoding="utf8") as f:
doc = BeautifulSoup(f.read(),"html.parser")
但是,您似乎想從 URL 中提取 HTML 檔案,而不是您計算機上的檔案。這可以這樣做:
from bs4 import BeautifulSoup
import requests
url = "https://www.duden.de/rechtschreibung/aufmachen"
req = requests.get(url)
soup = BeautifulSoup(req.text, "html.parser")
Bedeutungen = soup.body.findAll("div", {"id": "bedeutungen"})
print(Bedeutungen)
您的第一次呼叫.findAll()不起作用,因為textkwarg 在標簽內查找文本,而不是標簽本身。以下作業,但沒有特別的理由使用它而不是上面顯示的另一個。
tags = soup.body.findAll("div", class_="division", id="bedeutungen")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/496238.html
標籤:Python python-3.x 细绳 网页抓取 美丽的汤
下一篇:反正有沒有讓這段代碼更干凈?
