实例1:向百度或者360提交关键词并且获得搜索结果
百度关键词接口:https://www.baidu.com/s?wd=keyword
360关键词接口:https://www.so.com/s?q=keyword
import requests
keyword = "python"
try:
kv = {'wd':keyword} #360的为kv = {'q':keyword}
r = requests.get('https://www.baidu.com/s',params=kv) #360的为https://www.so.com/s
r.raise_for_status()
#print(r.status_code)
#print(r.request.url) #查看提交的URL
#print(len(r.text)) #查看返回的文本长度,单位是K
except:
print("爬取失败")
实例2:网络图片的爬取
网络图片一般链接:https://www.example.com/picture.jpg
或者找到某网站其中的一张图片,右键查看地址并观察格式
import requests
import os
url = 'http://img0.dili360.com/pic/2020/01/03/5e0ee523da2ad0t04429317.jpg@!rw9'
root = "D://pics//"
path = root +url.split('/')[-1]#保留图片的文件名
try:
if not os.path.exists(root): #判断路径是否存在
os.mkdir(root)
if not os.path.exists(path): #判断文件是否存在
r = requests.get(url)
with open(path,'wb') as f: #向路径中的文件写入请求返回的内容
f.write(r.content)
f.close()
print("图片保存成功")
else:
print("文件已经存在")
except:
print("爬取失败")
实例3:IP地址归属地的自动查询:使用ip138.com网站中的接口提交查询
import requests
url = 'http://m.ip138.com/ip.asp?ip='
try:
r = requests.get(url+'202.204.80.112')
r.raise_for_status()
r.encoding =r.apparent_encoding
print(r.text[-500:])
except:
print("爬取失败")