BeatutifulSoup基础

soup本身:

<p><a><a>111</a></a><a>222</a></p>


可以看到,1.soup.find和soup.find_all得到的结果包含查找标签本身;2.find的结果不是列表,find_all的结果是列表
>>> soup.find('p')
<p><a><a>111</a></a><a>222</a></p>
>>> soup.find_all('p')
[<p><a><a>111</a></a><a>222</a></p>]


接下来讨论子列的情况:

contents是将子列生成列表

soup.contents是将所有内容成为列表的一个元素

>>> soup.contents
[<p><a><a>111</a></a><a>222</a></p>]

soup.tag.contents,1.去除了本身的标签;2.平行子列标签成为列表的各个元素,但只生成一个列表

soup.find('p').contents
[<a><a>111</a></a>, <a>222</a>]


children和descendents都只能通过遍历得到,并且都不是列表

soup.children 得到所有内容,并且不是列表

>>> for i in soup.children:
	print(i)	
<p><a><a>111</a></a><a>222</a></p>

soup.tag.children 得到标签下的平行子列标签,也不是列表

>>> for i in soup.find('p').children:
	print(i)	
<a><a>111</a></a>
<a>222</a>

ps:

soup=BeautifulSoup('<p><c><a><d></d></a></c><c><a><d></d></a></c></p>','html.parser')

find_all查找到的所有tag组成列表,所以假如有平行的,就会有多个元素了

>>> soup.find_all('c')
[<c><a><d></d></a></c>, <c><a><d></d></a></c>]


一个tag find_all自己会生成空列表
>>> soup.p.find_all('p')
[]

contents本身生成列表,很好理解

>>> soup.find('p').contents
[<c><a><d></d></a></c>, <c><a><d></d></a></c>]

这是会生成多个列表的情况,先用children遍历出平行xml,但这些xml不组成列表,在对xml用find_all就会生成,各自的列表.

>>> for c in soup.find('p').children:
	print(c.find_all('a'))

	
[<a><d></d></a>]
[<a><d></d></a>]











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值