如何用python获取html标签内内容

 时间:2026-04-22 03:55:33

1、使用pip工具安装BeautifulSoup 模块,命令如下:

Python3以上 使用:

$ pip install BeautifulSoup4  

python2.7 使用命令:

$ pip install BeautifulSoup 

如何用python获取html标签内内容

2、导入BeautifulSoup 模块,代码如下:

from bs4 import BeautifulSoup

如何用python获取html标签内内容

3、创建一段html文档字符串,代码如下:

html_str= '''

<html>

  <head>

        <title></title>

  </head>

   <body>

        <div class="nav">百度经验</div>

     </body>

</html>

'''

如何用python获取html标签内内容

4、使用BeautifulSoup 加载html 文档,代码如下:

bs_xml = BeautifulSoup(html_str)

print(bs_xml.prettify())

如何用python获取html标签内内容

5、解析标签内容,代码如下:

div =bs_xml.findAll('div',{'class':'nav'})

div[0].contents

如何用python获取html标签内内容

6、全部代码:

from bs4 import BeautifulSoup

html_str= '''

<html>

  <head>

        <title></title>

  </head>

   <body>

        <div class="nav">百度经验</div>

     </body>

</html>

'''

bs_xml = BeautifulSoup(html_str)

print(bs_xml.prettify())

div =bs_xml.findAll('div',{'class':'nav'})

div[0].contents

  • python如何使用文本框
  • 背词达人APP如何修改个人头像
  • VB6.0如何绘制Timer控件
  • VS下的项目位置不受信任时警告用户属性如何关闭
  • VB编写红绿灯切换小程序
  • 热门搜索
    农行开户行怎么查 怎么更新win10 理科生可以报哪些专业 心眼小怎么办 私人定制旅游 附近旅游景区哪里好玩 黄褐斑怎么消除 自然乐园怎么样 齐装网怎么样 当我孤独的时候还可以抱着你