我正在尝试使用下面提到的代码获取特定标记的父元素:
# -*- 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
值。在
请帮助我解决这个问题,并原谅我的无知,因为我是新编程。在
.findParents()
没有按照您的想法操作。它查找与搜索匹配的当前元素的父元素。您正在尝试查找页面元素的父级,该元素已经是顶级元素。在如果你有这样的结构:
其中
^{pr2}$soup
是整个结构的BeautifulSoup变量,您可以通过以下方式找到span
:然后调用
.findParent('div')
将返回一个结果,即<div class="foo">
元素。在因此,在顶层元素上调用
.findParents()
将始终返回一个空结果,没有父元素。它的父元素调用了它。在相关问题 更多 >
编程相关推荐