python爬虫——简单框架

最易框架

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值