使用python在html中查找特定标记的父级时出现问题
我正在尝试使用下面提到的代码获取特定标记的父元素:使用python在html中查找特定标记的父级时出现问题,python,html,html-parsing,beautifulsoup,findall,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-o
# -*- 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
而不是parent,则它也返回None
值
我的实际问题与此类似
为了解决我的实际问题,我需要得到元素的父元素,对于这些元素,我将获得上面提到的None
值
请帮助我解决这个问题,并请原谅我的无知,因为我是编程新手。。findParents()
不会做您认为它会做的事情。它查找与搜索匹配的当前元素的父元素。您正在尝试查找页面元素的父元素,该元素已经是顶级元素
如果您有这样的结构:
<html>
<body>
<div class="foo">
<span id="bar">Some text</span>
</div>
</body>
</html>
然后调用.findParent('div')
将返回一个结果,即
元素
因此,在顶级元素上调用.findParents()
将始终返回空结果,因为没有父元素。在具有父元素的对象上调用它
spanelement = soup.find('span', id='bar')