2025年6月4日 星期三 乙巳(蛇)年 三月初八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

python解析html获取节点的内容(python小白笔记六)

时间:08-23来源:作者:点击数:24

在爬取网页的时候,爬下的数据需要解析html。如下代码。

使用python3.x

  • from bs4 import BeautifulSoup as bs
  • html='''<html>
  • <head>
  • <title class='ceshi'>super 哈哈 star</title>
  • </head>
  • <body>
  • 天下第一帅
  • <p class='sister'>
  • 是不是
  • </p>
  • <p id='seeyou'>haha嘻嘻</p>
  • </body>
  • </html>'''
  • str='''用BeautifulSoup解析数据 python3 必须传入参数二'html.parser' 得到一个对象,接下来获取对象的相关属性'''
  • html=bs(html,'html.parser')
  • # 读取title内容
  • print(html.title)
  • attrs=html.title.attrs
  • print(attrs)
  • print(attrs['class'][0]) #显示class里面的内容
  • print(html.body) #显示body内容
  • print(html.p.attrs)
  • print(html.select("#seeyou")[0].string) #解析id是seeyou的标签里卖弄的内容

输出结果:

  • D:\工具\pythonTools\CatchTest1101\venv\Scripts\python.exe D:/工具/pythonTools/CatchTest1101/venv/test/parse110602.py
  • <title class="ceshi">super 哈哈 star</title>
  • {'class': ['ceshi']}
  • ceshi
  • <body>
  • 天下第一帅
  • <p class="sister">
  • 是不是
  • </p>
  • <p id="seeyou">haha嘻嘻</p>
  • </body>
  • {'class': ['sister']}
  • haha嘻嘻
  • Process finished with exit code 0
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门