【问题标题】:Beautiful Soup parsing inline <div> and <p> into dictionaryBeautiful Soup 将内联 <div> 和 <p> 解析为字典
【发布时间】: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'

我正在参考以下类似的帖子,但我无法使结果正常工作,我认为它是我必须解析的文件。

Beautiful Soup parsing inline <div> and <p> into dictionary

【问题讨论】:

  • 请正确重新格式化 HTML
  • 我的文件是这样的

标签: python html parsing beautifulsoup


【解决方案1】:

您可以使用find_next() 并将值添加到dict

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')


output = {}
for tag in soup.select('h2 a'):
    output.setdefault(tag.get_text(), []).append(tag.find_next('p').get_text(strip=True, separator=' '))
    
print(output)

输出:

{'5 Points In-Line': ['2000 Highland Ave S Birmingham, AL 35205 (205) 930-8000'], 'Airport Blvd (AL)': ['4707 Airport Blvd Mobile, AL 36608 (251) 461-9933'], 'Alabama Power': ['600 18th St N Birmingham, AL 35203 (205) 257-1688']}

【讨论】:

  • 天啊,这救了我。无论如何要在 S 和 Birmingham 之间添加分隔符?
【解决方案2】:

只是为了回答您关于分离的问题并稍微接近您的预期输出,您可以执行以下操作。

&lt;p&gt; 获取文本时,使用替代分隔符代替空格,split() 使用string 生成带有分隔信息的list

示例 (dictionary comprehension)

{tag.get_text():tag.find_next('p').get_text(strip=True, separator='|').split('|') for tag in soup.select('h2  a')}

输出

{'5 Points In-Line': ['2000 Highland Ave S', 'Birmingham, AL 35205','(205) 930-8000'], 'Airport Blvd (AL)': ['4707 Airport Blvd', 'Mobile, AL 36608', '(251) 461-9933'], 'Alabama Power': ['600 18th St N', 'Birmingham, AL 35203', '(205) 257-1688']}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-10
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 2018-10-11
    • 2013-10-21
    相关资源
    最近更新 更多