注意:乱用爬虫违法,此文章仅做学习用途,禁止滥用!
关于网络爬虫,有很多萌新小白还不太了解。接下来我会为大家详细讲解爬虫的基础知识。
一、关于网站协议方面
一般网站都是用的http和https协议,这两个是服务器于你的设备的通讯方式。
这边HTTPS是加密的通讯方式,所以我先解析一下HTTP通讯『数据包』。
http数据包长这样:
get / http/1.1\n
host:www.baidu.com\n\n
(其中\n为换行符即回车)
这是一个最简单的http数据包,可以从服务端获取数据。
接下来是服务端发回来的数据包:
http/1.1 200 ok\n
server:nginxxxxxxx\n\n
你好,这是我的网站
我们可以使用socket模块(这是Python自带的)就能快速的处理这种请求
socket访问网站:
import socket#导入模块
rhost="www.baidu.com"#要访问的IP
rport=80#要访问的IP的端口,通常是443或者80
sendtext=b'GET / HTTP/1.1\r\nHOST: www.baidu.com\r\n\r\n'#访问的信息
cl=socket.socket(socket.AF_INET, socket.SOCK_STREAM)#TCP协议(因为HTTP协议是基于TCP的)
cl.connect((rhost,rport))#连接服务器
print("请求内容:\n%s"%sendte.decode())
cl.send(sendtext)#发送请求
response = cl.recv(4096)#接受请求
print(response.decode())#打印请求
cl.close()#关闭客户端
但如果服务端仅支持使用安全的https通讯协议怎么办呢?
没事我们并不需要自己慢慢研究这些解密,我们有现成的强大的python第三方库——requests!
利用requests我们就可以很好的处理https协议服务了!
requests的下载:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple requests
(注意要在Cmd命令提示符中输入)
requests访问网站:
import requests#导入模块
r=requests.get("https://www.baidu.com/")#访问百度
print(r.text)#数据
二、关于信息处理方面
对于信息处理方面,我们可以查找标签<img来寻找图片。
普通的寻找方法可能有点慢(为何不试试kmp呢),所以需要使用一些算法来加速。但实际再慢也可以在几秒内处理完一个页面。
requests的完整处理方式:
import requests#导入模块
import os#控制文件输入输出等
thehead={
'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'accept-encoding':'gzip, deflate, br, zstd',
'accept-language':'zh-CN,zh;q=0.9',
'cache-control':'max-age=0',
'connection':'keep-alive',
'cookie':'',
'host':'image.baidu.com',
'referer':'https://www.baidu.com/',
'sec-ch-ua':'"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
'sec-ch-ua-mobile':'?0',
'sec-ch-ua-platform':'"Windows"',
'sec-fetch-dest':'document',
'sec-fetch-mode':'navigate',
'sec-fetch-site':'same-origin',
'sec-fetch-user':'?1',
'upgrade-insecure-requests':'1',
'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
}#为了仿真Windows环境
d=input("Please enter the file that you want to save:")#保存文件
r=requests.get(input("Please enter the URL:"),headers=thehead)#网址
r.encoding='utf-8'#调整编码
infor=r.text#信息
os.system('mkdir %s'%d)#创建文件夹
with open("%s/index.html"%d,'w',encoding='utf-8')as f:
f.write(infor)#写入html代码
ptr=0
l=len(infor)
s='"thumbURL": "'
all=[]
while ptr<l:
try:
print('\r%d/%d'%(l,ptr),end='')
o=ptr
for u in s:
if infor[o]!=u:
ptr+=1
raise Exception('continue')
o+=1
j=o+1
while infor[j]!='"':
j+=1
all.append(infor[o:j])
ptr=j+1
except Exception as e:
if str(e)=='continue':
pass
else:
break
#以上是爬取img标签中的内容
print("\nFinish")
if all==[]:
print("No results!")
print(infor)
else:
print(all)
p=0
for i in all:
r=requests.get(i)
print('Response: %d'%r.status_code)
with open('%s/%d.jpeg'%(d,p),'wb')as f:
f.write(r.content)
p+=1
#然后逐个爬取
os.system("pause")