Code前端首页关于Code前端联系我们

Python数据科学教程:beautifulsoup类库读取并处理HTML页面

terry 2年前 (2023-09-25) 阅读数 50 #后端开发

有一个类库叫做beautifulsoup。您可以使用此库查找 html 标签的值并获取特定数据,例如页面标题和页面标题列表。

安装Beautifulsoup
使用Anaconda包管理器安装所需的包及其关联的包。

conda install Beaustifulsoap
Python

读取 HTML 文件

在下面的示例中,我们请求 python 环境的 url。然后使用html解析器参数读取整个html文件。然后打印 html 页面的前几行。

import urllib2
from bs4 import BeautifulSoup

# Fetch the html file
import urllib3
from bs4 import BeautifulSoup
# Fetch the html file
http = urllib3.PoolManager()
response = http.request('GET','http://www.yiibai.com/python/features.html')
html_doc = response.data
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')
# Format the parsed html file
strhtm = soup.prettify()
# Print the first few characters
print (strhtm[:225])
Python

执行上面的示例代码时,我们得到以下输出:

<!DOCTYPE html>
<!--[if IE 8]><html class="ie ie8"> <![endif]-->
<!--[if IE 9]><html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html>
 <!--<![endif]-->
 <head>
  <!-- Basic -->
  <meta charset="utf-8"/>
  <title>
Shell

提取标签值

您可以使用以下代码从标签的第一个实例中提取标签值。

import urllib3
from bs4 import BeautifulSoup
# Fetch the html file
http = urllib3.PoolManager()
response = http.request('GET','http://www.yiibai.com/python/features.html')
html_doc = response.data
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')

print (soup.title)
print(soup.title.string)
print(soup.a.string)
print(soup.b.string)
Python

执行上面的示例代码,您将得到以下结果:

<title>易百教程™ - 专注于IT教程和实例</title>
易百教程™ - 专注于IT教程和实例
None
友情链接:
Shell

提取所有标签

以下代码可以从所有实例中提取标签值。

import urllib3
from bs4 import BeautifulSoup
# Fetch the html file
http = urllib3.PoolManager()
response = http.request('GET','https://www.yiibai.com/python/features.html')
html_doc = response.data
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')


for x in soup.find_all('h1'): 
    print(x.string)
Python

运行上面的示例代码,得到以下结果 -

None
Python功能特点

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门