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

2018-09-3009:13:54后端程序开发Comments2,452 views字数 1597阅读模式

有一个类库叫作beautifulsoup。 使用这个库,可以搜索html标签的值,并获取页面标题和页面标题列表等特定数据。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

安装Beautifulsoup
使用Anaconda软件包管理器安装所需的软件包及其相关软件包。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

conda install Beaustifulsoap

读取HTML文件文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

在下面的例子中,我们请求一个url被加载到python环境中。 然后使用html parser参数来读取整个html文件。 接下来,打印html页面的前几行。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.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

当执行上面示例代码,得到以下输出结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

<!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

提取标记值文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

可以使用以下代码从标签的第一个实例中提取标签值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

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

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

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

提取所有标签文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

可以使用以下代码从标签的所有实例中提取标签值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

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

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html

None
Python功能特点
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/6042.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/6042.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定