Python数据科学 专题
您的位置:python > Python数据科学专题 > Python读取HTML页面
Python读取HTML页面
作者:--    发布时间:2019-11-20

有一个类库叫作beautifulsoup。 使用这个库,可以搜索html标签的值,并获取页面标题和页面标题列表等特定数据。

安装beautifulsoup
使用anaconda软件包管理器安装所需的软件包及其相关软件包。

conda install beaustifulsoap

读取html文件

在下面的例子中,我们请求一个url被加载到python环境中。 然后使用html parser参数来读取整个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.h3.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])

当执行上面示例代码,得到以下输出结果 -

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

提取标记值

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

import urllib3
from bs4 import beautifulsoup
# fetch the html file
http = urllib3.poolmanager()
response = http.request('get','http://www.h3.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)

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

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

提取所有标签

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

import urllib3
from bs4 import beautifulsoup
# fetch the html file
http = urllib3.poolmanager()
response = http.request('get','https://www.h3.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)

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

none
python功能特点

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册