如何用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编写红绿灯切换小程序
  • 热门搜索
    清炖牛肉的做法 腌辣椒的做法大全 苹果怎么清理垃圾 vivo手机怎么截屏 鱿鱼怎么做好吃 苹果酱的做法 蒜苗的做法 蚝油生菜的做法步骤 缪怎么读 蛋糕做法大全