我有一個帶有鏈接和日期的長表。請參閱下面的 HTML 代碼。表格中的資料結構良好:所有資訊都顯示在塊中,標簽之間有日期(isodate),dt標簽之間有鏈接dd。
使用 Python 和 BeautifulSoup,我想獲取每個塊的日期和鏈接。
<dt isodate="2022-02-10">
<div class="date">10 February 2021</div>
</dt>
<dd>
<div class="testa"><span class="testy"><a class="row" href="https://www.bla.html" lang="en"> <span class="full">English</span></a></span></div>
</dd>
<dt isodate="2022-02-12">
<div class="date">12 February 2021</div>
</dt>
<dd>
<div class="testa"><span class="testy"><a class="row" href="https://www.bli.html" lang="en"> <span class="full">English</span></a></span></div>
</dd>
如何做到這一點?
uj5u.com熱心網友回復:
您可以使用漂亮的湯find_all和find_next_sibling方法來選擇dts 和兄弟dds,如下所示:
from bs4 import BeautifulSoup
html_doc = """
<dt isodate="2022-02-10">
<div >10 February 2021</div>
</dt>
<dd>
<div ><span ><a href="https://www.bla.html" lang="en"> <span >English</span></a></span></div>
</dd>
<dt isodate="2022-02-12">
<div >12 February 2021</div>
</dt>
<dd>
<div ><span ><a href="https://www.bli.html" lang="en"> <span >English</span></a></span></div>
</dd>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
items = []
for item in soup.find_all('dt'):
date = item.get('isodate')
url = item.find_next_sibling('dd').select_one('div a').get('href')
# add a dict to the items list
items.append(dict(date=date, url=url))
print(items)
輸出
[
{'date': '2022-02-10', 'url': 'https://www.bla.html'},
{'date': '2022-02-12', 'url': 'https://www.bli.html'}
]
uj5u.com熱心網友回復:
這里 index.html 由
<html>
<body>
<dt isodate="2022-02-10"><div class="date">10 February 2021</div></dt>
<dd>
<div class="testa"><span class="testy"><a class="row" href="https://www.bla.html" lang="en"> <span
class="full">English</span></a></span></div></dd>
<dt isodate="2022-02-12"><div class="date">12 February 2021</div></dt>
<dd>
<div class="testa"><span class="testy"><a class="row" href="https://www.bli.html" lang="en"> <span
class="full">English</span></a></span></div></dd>
</body>
</html>
使用的 Python 代碼:
from bs4 import BeautifulSoup
with open("index.html") as html_content:
soup = BeautifulSoup(html_content, 'html.parser')
date = [x.get_text() for x in soup.find_all('div',class_='date')]
link = [x['href'] for x in soup.find_all('a',href=True)]
- 日期:
find_all 將找到 div class = 'div' 并回傳所有匹配標簽的串列。
[<div class="date">10 February 2021</div>, <div class="date">12 February 2021</div>]
從這里您可以通過以下方式提取日期x.get_text()
- 對于鏈接:
find_all 將找到包含 href 值的 a 標簽(當 href=True 時)并回傳所有匹配標簽的串列。
[<a class="row" href="https://www.bla.html" lang="en"> <span class="full">English</span></a>, <a class="row" href="https://www.bli.html" lang="en"> <span class="full">English</span></a>]
從這里您可以使用提取 href 資料x['href']
輸出:可以單獨訪問日期和 URL 串列。
['10 February 2021', '12 February 2021'] ['https://www.bla.html', 'https://www.bli.html']
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/431743.html
上一篇:使用VBA進行網頁抓取
