python网络爬虫学习笔记(1)
作者:赖权华 时间:2023-12-24 04:08:16
本文实例为大家分享了python网络爬虫的笔记,供大家参考,具体内容如下
(一) 三种网页抓取方法
1、 正则表达式:
模块使用C语言编写,速度快,但是很脆弱,可能网页更新后就不能用了。
2、Beautiful Soup
模块使用Python编写,速度慢。
安装:
pip install beautifulsoup4
3、 Lxml
模块使用C语言编写,即快速又健壮,通常应该是最好的选择。
(二) Lxml安装
pip install lxml
如果使用lxml的css选择器,还要安装下面的模块
pip install cssselect
(三) 使用lxml示例
import urllib.request as re
import lxml.html
#下载网页并返回HTML
def download(url,user_agent='Socrates',num=2):
print('下载:'+url)
#设置用户代理
headers = {'user_agent':user_agent}
request = re.Request(url,headers=headers)
try:
#下载网页
html = re.urlopen(request).read()
except re.URLError as e:
print('下载失败'+e.reason)
html=None
if num>0:
#遇到5XX错误时,递归调用自身重试下载,最多重复2次
if hasattr(e,'code') and 500<=e.code<600:
return download(url,num-1)
return html
html = download('https://tieba.baidu.com/p/5475267611')
#将HTML解析为统一的格式
tree = lxml.html.fromstring(html)
# img = tree.cssselect('img.BDE_Image')
#通过lxml的xpath获取src属性的值,返回一个列表
img = tree.xpath('//img[@class="BDE_Image"]/@src')
x= 0
#迭代列表img,将图片保存在当前目录下
for i in img:
re.urlretrieve(i,'%s.jpg'%x)
x += 1
来源:https://www.cnblogs.com/simple-free/p/8757758.html
标签:python,爬虫,网络爬虫
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pyenv与virtualenv安装实现python多版本多项目管理
2022-12-19 23:50:04
![](https://img.aspxhome.com/file/2023/8/112108_0s.png)
python同义词替换的实现(jieba分词)
2022-02-10 20:58:00
![](https://img.aspxhome.com/file/2023/1/77021_0s.png)
Python 读取串口数据,动态绘图的示例
2021-11-15 19:36:24
![](https://img.aspxhome.com/file/2023/0/115200_0s.jpg)
python logging模块的分文件存放详析
2023-04-02 20:27:32
![](https://img.aspxhome.com/file/2023/8/97538_0s.png)
go variant底层原理深入解析
2024-05-22 17:45:08
![](https://img.aspxhome.com/file/2023/0/125100_0s.png)
Python映射类型之dict详解
2023-08-03 13:19:19
python模拟登录百度贴吧(百度贴吧登录)实例
2023-11-20 14:30:56
![](https://img.aspxhome.com/file/2023/4/63614_0s.jpg)
Python自动发送邮件的方法实例总结
2023-05-21 02:53:42
![](https://img.aspxhome.com/file/2023/5/93995_0s.png)
mssqlserver恢复ldf文件数据的方法
2024-01-22 11:06:54
python实现Excel文件转换为TXT文件
2021-01-15 05:24:54
Python SSL证书验证问题解决方案
2022-11-06 13:54:35
![](https://img.aspxhome.com/file/2023/6/118056_0s.png)
Python使用RSA库加密和解密
2023-04-23 02:46:29
php实现图片转换成ASCII码的方法
2023-09-07 12:10:57
python使用paramiko模块通过ssh2协议对交换机进行配置的方法
2022-05-16 03:03:17
详谈Pandas中iloc和loc以及ix的区别
2022-01-30 00:52:49
JavaScript错误处理
2023-09-23 08:26:37
详解php处理大并发大流量大存储
2023-07-21 13:11:02
![](https://img.aspxhome.com/file/2023/8/555181_0s.jpg)
python 实现数组list 添加、修改、删除的方法
2021-10-21 16:27:34
详解scratch3.0二次开发之scratch-blocks中的blocks的类型、定义和使用方法
2023-10-18 06:02:09
![](https://img.aspxhome.com/file/2023/9/132389_0s.png)
对Python强大的可变参数传递机制详解
2021-06-23 02:54:09