BeautifulSoup:在定位div之后查找其他元素

2024-09-19 23:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个页面中,我有以下HTML

<div class="ProfileDesc">
<p>
    <span class="Title">Name</span>
    <span>Tom Ready</span>
</p>
<p>
    <span class="Title">Born</span>

<span>
    <bxi> 10 Jan 1960</bxi> 
<p>
    <span class="Title">Death</span>
    <span>
        <bxi> 01 Jun 2019</bxi>
    </span>
</p>
</div>

下面的代码用于从整个页面中提取ProfileDesc

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

mydivs = soup.find("div", {"class": "ProfileDesc"})

我想要以下输出

Name: Tom Ready
Born: 10 Jan 1960
Death: 01 Jun 2019

找到ProfileDesc后如何提取这些文件


Tags: namedivtitle页面junjanclassspan
3条回答

“1960年1月10日”之后的html代码没有结束p标记

name = soup.find('span',string='Name').parent.text.replace('Name','').strip()
born = soup.find('span',string='Born').parent.text.replace('Born','').strip()
death = soup.find('span',string='Death').parent.text.replace('Death','').strip()
print(f'Name: {name}')
print(f'Born: {born}')
print(f'Death: {death}')

当您非常确定DOM结构时:

mydivs = soup.find("div", {"class": "ProfileDesc"})

for element in mydivs.find_all("p"):
    title = element.find("span")
    content = title.findNext("span")
    print("%s : %s" % (title.text.strip(), content.text.strip()))

输出:

Name : Tom Ready
Born : 10 Jan 1960
Death : 01 Jun 2019

试试这个

keys_ = set() # avoid duplicate keys

for p in mydivs.find_all("p"):
    ss = list(p.stripped_strings)

    for k, v in zip(ss[::2], ss[1::2]):
        if k in keys_:
            continue
            
        keys_.add(k)
        print(k, ":", v)

Name : Tom Ready
Born : 10 Jan 1960
Death : 01 Jun 2019

相关问题 更多 >