python3爬虫获取html内容及各属性值的方法
作者:android-李志强 时间:2021-08-23 02:37:33
今天用到BeautifulSoup解析爬下来的网页数据
首先导入包from bs4 import BeautifulSoup
然后可以利用urllib请求数据
记得要导包
import urllib.request
然后调用urlopen,读取数据
f=urllib.request.urlopen(‘http://jingyan.baidu.com/article/455a9950bc94b8a166277898.html‘)
response=f.read()
这里我们就不请求数据了,直接用本地的html代码,如下
注意:”'xxx”'是多行注释
#python3
from bs4 import BeautifulSoup
html='''<html>
<head>
<title class='ceshi'>super 哈哈 star</title>
</head>
<body>
天下第一帅
<p class='sister'>
是不是
</p>
</body>
</html>'''
#用BeautifulSoup解析数据 python3 必须传入参数二'html.parser' 得到一个对象,接下来获取对象的相关属性
html=BeautifulSoup(html,'html.parser')
# 读取title内容
print(html.title)
# 读取title属性
attrs=html.title.attrs
print(attrs)
# 获取属性attrs['class'] ---->['ceshi'] 这是一个list 通过下标可以获取值
print(attrs['class'][0])
# 读取body
print(html.body)
读取数据还可以通过BeautifulSoup的select方法
html.select()
#按标签名查找
soup.select('title')
soup.select('body')
# 按类名查找
soup.select('.sister')
# 按id名查找
# p标签中id为link的标签
soup.select('p #link')
#取标签里面的值
soup.p.string
#取标签里属性值 通过href获取
html['href']
来源:https://blog.csdn.net/lzq520210/article/details/76855606
标签:python3,爬虫,html,属性值
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用css制作星级投票评分功能
2008-01-08 21:12:00
![](https://img.aspxhome.com/file/UploadPic/20071/2007131101422899s.gif)
pytorch中的model=model.to(device)使用说明
2023-02-23 15:07:48
教你快速掌握更改表中列顺序的好方法
2008-11-27 17:14:00
使用一条INSERT语句完成多表插入
2010-03-18 11:08:00
MySQL数据库性能优化妙招
2009-03-20 13:13:00
php设置编码格式的方法
2023-11-14 12:01:22
Python提取支付宝和微信支付二维码的示例代码
2021-04-08 19:38:42
![](https://img.aspxhome.com/file/2023/2/70242_0s.jpg)
python 捕获 shell/bash 脚本的输出结果实例
2023-10-04 15:27:41
Python基于pyecharts实现关联图绘制
2021-04-08 12:05:45
![](https://img.aspxhome.com/file/2023/7/80397_0s.png)
Python3+pycuda实现执行简单GPU计算任务
2022-06-04 09:55:29
![](https://img.aspxhome.com/file/2023/6/72136_0s.png)
js动态显示当前日期,时间和星期代码
2007-08-14 12:31:00
python如何运行js语句
2022-04-10 02:34:27
![](https://img.aspxhome.com/file/2023/3/81603_0s.png)
解决Django加载静态资源失败的问题
2023-09-11 21:10:51
![](https://img.aspxhome.com/file/2023/2/76832_0s.jpg)
Python使用SQLite和Excel操作进行数据分析
2023-11-27 22:32:28
LINUX下Oracle数据导入导出的方法详解
2023-07-06 15:20:32
交互设计实用指南系列(10)—别让我思考
2010-03-01 12:50:00
挑战! 纯Javascript 重现经典网游! <魔力宝贝>
2008-10-04 10:37:00
![](https://img.aspxhome.com/file/UploadPic/200810/4/2008104104524850s.jpg)
python实现百度文库自动化爬取
2023-02-01 23:57:22
jQuery中文入门教程
2007-12-09 19:20:00
![](https://img.aspxhome.com/file/UploadPic/up/2007120919444529.gif)
关于Python中浮点数精度处理的技巧总结
2021-12-28 15:12:53
![](https://img.aspxhome.com/file/2023/9/79589_0s.jpg)