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

2025-11-21 19:36:30

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢