Skip to main content
 首页 » 编程设计

python之BeautifulSoup:如何跳过 find_all 中的子节点

2024年10月24日11lyj

我有以下代码来抓取此页面:

soup = BeautifulSoup(html) 
result = u'' 
# Find Starting point 
start = soup.find('div', class_='main-content-column') 
if start: 
    news.image_url_list = [] 
    for item in start.find_all('p'): 

我面临的问题是它也捕获了 <p>里面<div class="type-gallery"> ,我想避免。但是找不到实现它的方法。 有什么想法吗?

请您参考如下方法:

您想要直接子代,而不仅仅是任何后代,这就是element.find_all() 返回的内容。你最好的选择是使用 CSS selector相反:

for item in soup.select('div.main-content-column > div > p'): 

> 运算符将此限制为 p 标记,这些标记是 div 中 div 标记的直接子节点> 与给定的类(class)。您可以根据需要将其具体化;添加 itemprop 属性,例如:

for item in soup.select('div.main-content-column > div[itemprop="articleBody"] > p'): 

另一种方法是遍历 element.children iterable :

start = soup.find('div', class_='main-content-column') 
if start: 
    news.image_url_list = [] 
    for item in start.children: 
        if item.name != 'div': 
            # skip children that are not <div> tags 
            continue 
        for para in item.children: 
            if item.name != 'p': 
                # skip children that are not <p> tags 
                continue