Skip to main content
 首页 » 编程设计

Python BeautifulSoup 从父/兄弟关系中获取内容

2025年05月04日20birdshome

html 的一部分结构如下。我想从中获得工作“标题”和“时间”。我可以单独获取它们,例如:

from bs4 import BeautifulSoup 
 
 
pages = '<div class="content"> \ 
                <a href="Org"> \ 
                        <h3 class="title"> \ 
                            Dep. Manager</h3> \ 
                        </a> \ 
                <div class="contributor"></div> \ 
                <p>John</p> \ 
                <time class="time"> \ 
                        <span class="timestamp">May 02 2016</span> \ 
                    </time> \ 
                </div>' 
 
 
soup = BeautifulSoup(pages, "lxml") 
 
 
soup.prettify() 
 
 
s = soup.find_all(class_ = "title")[0] 
 
t = soup.find_all('span', class_ = "timestamp")[0].text.strip() 
 
 
pp_title = s.text.strip() 
 
print t 
 
print (pp_title) 

它返回我想要的。

Dep. Manager 
May 02 2016 

对于“时间”,我想要另一种方式来获取它,因为“时间”总是在“标题”下方。我试过这条线来获取“时间”,它不起作用。

print (s.parent.next_sibling.next_sibling) 

从关系到“标题”的“时间”的正确方法是什么?谢谢。

请您参考如下方法:

您可以通过指定详细信息findParent:

t = s.findParent("div", class_='content').find('span', class_='timestamp').text.strip() 

例子:

titles = soup.find_all(class_="title") 
for title in titles: 
    timestamp = title.findParent("div", class_='content').find('span', class_='timestamp').text.strip() 
    print(title.text.strip(), timestamp)