html python标签_问题与使用python的HTML中找到特定标签的父

I am trying to fetch parent element of a particular tag using below mentioned code:

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

Problem: Output which I am getting after running this code returns Null array [], if I use findParent instead of Parents then also it returns None value.

To solve my actual problem I need to get parents of elements for which I am getting None value as mentioned above.

Please help me in solving this issue and pardon my ignorance as I am new to programming.

解决方案

.findParents() does not do what you think it does. It finds the parents of the current element that match the search. You are trying to find the parents of a page element, which is already the top-level element.

If you had a structure like this:

Some text

where soup is a BeautifulSoup variable for the whole structure, you can find the span with:

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

and then calling .findParent('div') will return a result, namely the

element.

So, calling .findParents() on a top-level element will always return an empty result, there are no parents. Call it on something that does have a parent element instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值