python第一个html页面,Python读取HTML页面

本篇文章帮大家学习python读取HTML页面,包含了Python读取HTML页面使用方法、操作技巧、实例演示和注意事项,有一定的学习价值,大家可以用来参考。

有一个类库叫作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.jikedaquan.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])

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

提取标记值

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

import urllib3

from bs4 import BeautifulSoup

# Fetch the html file

http = urllib3.PoolManager()

response = http.request('GET','http://www.jikedaquan.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)

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

易百教程™ - 专注于IT教程和实例

易百教程™ - 专注于IT教程和实例

None

友情链接:

提取所有标签

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

import urllib3

from bs4 import BeautifulSoup

# Fetch the html file

http = urllib3.PoolManager()

response = http.request('GET','https://www.jikedaquan.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功能特点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值