【发布时间】:2023-03-06 19:48:01
【问题描述】:
我有一组共享以下结构的 HTML 文件:
<h1>ITEM NAME</h1>
<span class="standardLabel">Place of publication: </span>PLACENAME
<br /><span class="standardLabel">Publication dates: </span>DATE
<br /><span class="standardLabel">Notes: </span>NOTES
<br /><span class="standardLabel">Frequency: </span>FREQUENCY
我要提取的是所有以粗体表示的信息,但我只能编写一个捕获“项目名称”和“地名”的脚本:
# import packages
from bs4 import BeautifulSoup
import os
from os.path import dirname, join
directory=("C:\\Users\\mobarget\\Google Drive\\ACADEMIA\\10_Data analysis_PhD\\NLI Newspaper DB")
# search information in each file
for infile in os.listdir(directory):
filename=join(directory, infile)
indata=open(filename,"r", encoding="utf-8", errors="ignore")
contents = indata.read()
soup = BeautifulSoup(contents,'html')
newspaper=soup.find('h1')
if newspaper:
print("Title of file no.", str(infile), ": ", newspaper)
place=soup.find("span",{"class":"standardLabel"}).next_sibling
print(place)
else:
continue
输出是:
Title of file no. 1 : <h1>About Town</h1>
Dungannon, Co. Tyrone
Title of file no. 10 : <h1>Amárach: Guth na Gaeltachta</h1>
Dublin, Co. Dublin
Title of file no. 100 : <h1>Belfast Election</h1>
Belfast, Co. Antrim
[等]
有什么想法可以在不使代码过于冗余的情况下提取丢失的数据吗?
【问题讨论】:
标签: html python-3.x beautifulsoup