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

2024-10-02 18:26:42 发布

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

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

# -*- 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

问题:运行此代码后得到的输出返回空数组[],如果我使用findParent而不是父数组,那么它也返回None值。在

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

为了解决我的实际问题,我需要获取元素的父元素,我将获得上面提到的None值。在

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


Tags: 代码from标记importnone元素数组urllib2
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:42

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

如果你有这样的结构:

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

其中soup是整个结构的BeautifulSoup变量,您可以通过以下方式找到span

^{pr2}$

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

因此,在顶层元素上调用.findParents()将始终返回一个空结果,没有父元素。它的父元素调用了它。在

相关问题 更多 >