我是 python 網路抓取的新手。我正在嘗試構建一個腳本,該腳本僅從網站上獲取粗體下的正常文本 - https://www.state.gov/cuba-restricted-list/list-of-restricted-entities-and-subentities-related -with-cuba-effective-january-8-2021/
即,僅像文本 MINFAR — Ministryio de las Fuerzas Armadas Revolucionarias 和 MININT —部委下的內政部長類似地直到Habaguanexand 的附加子物體結束,并將它們存盤為串列。我嘗試使用以下代碼獲取它們。但我無法單獨獲取那些正常的文本值。
這是我的代碼:
import requests
import re
from bs4 import BeautifulSoup
URL = "https://www.state.gov/cuba-restricted-list/list-of-restricted-entities-and-subentities-associated-with-cuba-effective-january-8-2021/"
page = requests.get(URL)
soup = BeautifulSoup(page.text, "lxml")
content = soup.find_all(lambda tag: tag.name == 'div' and tag.get('class') == ['entry-content'])
print(content)
任何想法都衷心歡迎朋友。請隨時分享您的想法。先感謝您 :)
uj5u.com熱心網友回復:
我查看了該站點的 HTML 代碼,以了解它具有什么樣的格式。似乎所有專案都包含在一個 div 中,entry-content并且您也發現了自己的類。
然后我也發現所有的文字都是用<p>tags包裹的,但是我們要排除的headers也是包裹在<b>這個p標簽內的tags里面。這意味著我們可以過濾掉任何以標簽開頭的<b>標簽。重要的是我們只過濾掉以 開頭的標簽,<b>因為有一些有效的條目,比如<p>Gran Hotel Bristol Kempinski <b><i>Effective</i></b><b><i>November 15</i></b><b><i>, 2019</i></b></p>串列中的條目,但在包裝<p>標簽后面只有粗體標簽。
在腳本中,我p.encode_contents()用來將 HTML 作為字串獲取,以查看它是否以<b>標簽開頭。請注意,此函式回傳一個位元組串,因此必須使用 與另一個位元組串進行比較b""。
還有一點是它跳過了前兩個標簽,因為它們屬于頁面的描述。
import requests
from bs4 import BeautifulSoup
URL = "https://www.state.gov/cuba-restricted-list/list-of-restricted-entities-and-subentities-associated-with-cuba-effective-january-8-2021/"
page = requests.get(URL)
soup = BeautifulSoup(page.text, "lxml")
content = soup.find_all("div", {"class": "entry-content"})[0]
results = []
for p in content.find_all('p')[2:]:
if not p.encode_contents()[:3] == b"<b>" and p.text:
results.append(p.text)
print(results)
此代碼遍歷<p>標記中的所有.entry-content標記,并檢查它是否以<b>標記開頭。然后只保存那些不保存的文本。最后它只列印包含所有名稱的陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/361643.html
