使用python在html中查找特定标记的父级的问题

时间:2013-01-03 08:15:08

标签: python html html-parsing beautifulsoup findall

我正在尝试使用下面提到的代码获取特定标记的父元素:

# -*- coding: cp1252 -*-
import csv
import urllib2
import sys
import time
from bs4 import BeautifulSoup
from itertools import islice
page1= urllib2.urlopen('http://www.sfr.fr/mobile/telephones?vue=000029&tgp=toutes-les-offres&typesmartphone=se-android&typesmartphone=se-apple&typesmartphone=se-bada&typesmartphone=se-rim-blackberry&typesmartphone=se-windows&p=0').read()
soup1 = BeautifulSoup(page1)
price_parent = soup1.findParents('div')
print price_parent

问题:运行此代码后我得到的输出返回Null数组[],如果我使用findParent代替Parent,那么它还会返回None值。

我的实际问题与此BeautifulSoup - findAll not within certain tag

类似

要解决我的实际问题,我需要获取元素的父母,我将获得None值,如上所述。

请帮我解决这个问题并原谅我的无知,因为我是编程新手。

1 个答案:

答案 0 :(得分:0)

.findParents()没有按照您的想法行事。它找到与搜索匹配的当前元素的父级。您正在尝试查找页面元素的父项,该元素已经是顶​​级元素。

如果你有这样的结构:

<html>
    <body>
        <div class="foo">
            <span id="bar">Some text</span>
        </div>
    </body>
</html>

其中soup是整个结构的BeautifulSoup变量,您可以找到span

spanelement = soup.find('span', id='bar')

然后调用.findParent('div')将返回一个结果,即<div class="foo">元素。

因此,在顶级元素上调用.findParents()始终返回空结果,不是父级。在具有父元素的东西上调用它。