soup本身:
<p><a><a>111</a></a><a>222</a></p>
>>> 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>]
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>]
>>> 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>]