ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Beautiful选择器/遍历文档树Day3-7

2019-07-03 18:53:12  阅读:170  来源: 互联网

标签:Beautiful 获取 list Day3 选择器 soup html print 节点


#!/usr/bin/env python
#coding: utf8
#python2
#Beautiful选择器
from bs4 import BeautifulSoup
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="sister"><b>$37</b></p>

<p class="story" id="p">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" >Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc,'lxml')
#遍历文档树
#1.直接使用 重点
print(soup.html)
print(type(soup.html))
print(soup.a)
print(soup.p)

#2.获取标签的名称
print(soup.a.name)

#3.获取标签的属性 重点
print(soup.a.attrs) #获取a标签中的所有属性
print(soup.a.attrs['href'])

#4.获取标签的文本内容 重点
print(soup.a.text)

#5.嵌套选择
print(soup.html.body.p)

#6.子节点、子孙节点
print(soup.p.children) #返回迭代器对象
print((list(soup.p.children)))

#7.父节点、祖先节点
print(soup.b.parent)
print(soup.b.parents)
print(list(soup.b.parents))

#8.兄弟节点
print(soup.a)
#下一个兄弟节点
print(soup.a.next_sibling)

#获取下一个兄弟的所有节点,返回的是一个生成器
print(soup.a.next_siblings)
print(list(soup.a.next_siblings))

#获取上一个兄弟节点
print(soup.a.previous_sibling)
#获取上一个的所有兄弟节点,返回的是一个生成器
print(list(soup.a.previous_siblings))

 

标签:Beautiful,获取,list,Day3,选择器,soup,html,print,节点
来源: https://www.cnblogs.com/zxdhahaha/p/11128293.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有