python爬虫基础知识—01request库学习

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yulizan9165/article/details/89197526

1、requests库
import requests
r=requests.get("http://www.baidu.com")
r.status_code
r.encoding='utf-8'
print(r.text)
requests的方法
https://www.jianshu.com/p/c4e401d57e64
https://blog.csdn.net/weixin_42549725/article/details/81012604

2、requests的异常
https://blog.csdn.net/zhangyu4863/article/details/80233826
r.raise_for_status 如果正常返回200 否则返回异常

3、爬取网页的通用代码框架
import requests
def getHTMLText(url):
    r=requests.get(url,timeout=30)
    r.raise_for_status()
    r.encoding=r.apparent_encoding
    return r.text

if __name__=="__main__":
    url="http://www.baidu.com"
    print(getHTMLText(url))
    
4、http 超文本传输协议
url格式:http://host[:post][path]

5、requests的post方法
import requests
payload={"key1":"value1","key2":"value2"}
r=requests.post("http://httpbin.org/post",data=payload)
print(r.text)
会默认存到form表单
patch会覆盖原有内容
requests.post(url,data=None,json=None,**kwargs)

6、request方法是最基本的方法

requests.request(method,url,**kwargs)
method:请求方式,对应get/post/put等,共7种
参数:
params:字典或字节序列,作为参数增加到url中
data不放在URL链接,而是作为数据存放在URL对应的位置
json:JSON格式的数据,作为request的内容
headers:字典,http定制头
hd={'user-agent':'Chrome/10'}
r=requests.request('POST','http://python123.io/ws',headers==hd)
cookies:从http协议中解析cookies,可以是字典
auth:元组,支持http认证功能
files:字典类型,传输文件
fs={'file':open('data.xls','rb')}
r=requests.request('POST','http://python123.io/ws',files=fs)
timeout:设置超时时间,单位为秒
proxies:字典类型。设定访问代理服务器,可以增加登录认证
pxs={'http':'http://userzz:[email protected]:1234'
     'https':'https://10.10.10.1:4321'    }
r=requests.request('GET','http://www.baidu.com',proxies=pxs)
使用这个可以隐藏用户爬取网页时原的ip地址
allow_redirects,stream,verify,cert---一些高级应用

猜你喜欢

转载自blog.csdn.net/yulizan9165/article/details/89197526