最易框架
import requests
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败")
对于限制某些爬虫进入的网站,我们需要更改user-agent,如爬取亚马逊商品信息:
import requests
try:
kv={'user-agent':'Mozilla/5.0'}#通过游览器访问
r=requests.get(url,headers=kv)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[1000:2000])
except:
print("爬取失败")
搜索引擎关键词提交接口
百度的关键词接口:
http://www.baidu.com/s?wd=keyword
import requests
try:
kv={'wd':keyword}
r=requsets.get("http://www.baidu.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
网络图片的爬取
我们选取一张怪猎世界的图片,其地址为:
https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1609572265,2857939699&fm=26&gp=0.jpg
import requests
import os
url="https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1609572265,2857939699&fm=26&gp=0.jpg"
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("爬取失败")
IP地址查询
import requests
url="http://m.ip138.com/ip.asp?ip="
try:
r=requests.get(url+'202.120.189.78')
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.rext[-500:])
except:
print("爬取失败")
注意以上的 with as 的使用:
https://zhuanlan.zhihu.com/p/26487659