【发布时间】:2021-10-29 01:20:37
【问题描述】:
我正在为位置存储数据处理 HTML 的混乱部分,并且很难干净地解析它。我在这里阅读了其他几篇文章,但没有任何成功的工作。
以下是 HTML 的一部分,来自 txt 文件:
"
^ class=""location"">
<h2>
<a href=""/Locations/AL/5-Points-In-Line"">5 Points In-Line</a>
</h2>
<p>
2000 Highland Ave S
<br/>
Birmingham, AL 35205
<br/>
(205) 930-8000
</p>
</div>
^ class=""location"">
<h2>
<a href=""/Locations/AL/Airport-Blvd-AL"">Airport Blvd (AL)</a>
</h2>
<p>
4707 Airport Blvd
<br/>Mobile, AL 36608
<br/>
(251) 461-9933 </p>
</div>
^ class=""location"">
<h2>
<a href=""/Locations/AL/Alabama-Power"">Alabama Power</a>
</h2>
<p>
600 18th St N
<br/>Birmingham, AL 35203
<br/>
(205) 257-1688 </p>
</div>
我需要的是'a'(位置)作为键和'p'中的地址信息作为字典中的值。问题还在于地址部分中的所有 br/。
理想情况下我想要:
{'5-Points-In-Line':['2000 Highland Ave S','Birmingham AL 35205','(205)930-8000'],...]
这是我目前所拥有的,但与此不相近: 从 bs4 导入 BeautifulSoup
#import 位置表
with open('AL.txt','r') as f:
contents = f.read()
soup = BeautifulSoup(contents, 'html.parser')
result = {}
for div in soup.find_all('div'):
for h in soup.find_all('h2'):
location = h.find('a').text
for p in soup.find_all('p'):
p = p.text.replace('\n','|').replace('\t','').strip()
clean = ' '.join(p.split()).replace('| ','|').replace(' |','|').replace('||','|')
address_clean = clean.replace('| ','|').replace(' |','|').replace('||','|')
result[location].append[address_clean]
result
获取 KeyError: '5 Points In-Line'
我正在参考以下类似的帖子,但我无法使结果正常工作,我认为它是我必须解析的文件。
【问题讨论】:
-
请正确重新格式化 HTML
-
我的文件是这样的
标签: python html parsing beautifulsoup