|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 payton24 于 2018-1-18 09:56 编辑
最近开始主要看网络爬虫的书,有时顺利,有时还碰到挺多障碍的。
也是时候总结一下怎么做了。
相对于urllib模块,感觉requests模块使用起来更加便利,也容易安装,pip install requests就搞定了。
1. 最简单的例子:
- import requests
- r = requests.get("http://www.baidu.com")
- print(r.encoding) #文本编码
- print(r.status_code) #响应状态
- print(r.text) #返回str类型的响应内容,根据响应头部的字符编码进行解码。
- print(r.content) #返回bytes类型的响应内容,会自动解码gzip和deflate编码。
复制代码
2. 定制requests
可以用http://www.httpbin.org/进行测试,方便快捷。
①定制请求头,一般加上User-Agent,还可以添加Host等部分。
- import requests
- hds={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
- r = requests.get("http://www.httpbin.org/user-agent")
- r1 = requests.get("http://www.httpbin.org/user-agent",headers=hds)
- print(r.text)
- print(r1.text)
复制代码
②定制超时
- r2 = requests.get("http://www.httpbin.org/user-agent",headers=hds,timeout=15)
- print(r2.text)
复制代码
③传递URL信息,用于在URL中加入特定数据,构建新的URL。
- key_dict={'wd':'python'}
- r3 = requests.get("http://www.httpbin.org/get",params=key_dict)
- r4 = requests.get("http://www.baidu.com/s",params=key_dict)
- print(r3.text)
- print(r4.text)
复制代码
④发送Post请求
- key_dict={'Pw':'python'}
- r5 = requests.post("http://www.httpbin.org/post",data=key_dict)
- print(r5.text)
复制代码
3.最后附上requests的get、post方法说明。
requests.get方法
- Help on function get in module requests.api:
- get(url, params=None, **kwargs)
- Sends a GET request.
-
- :param url: URL for the new :class:`Request` object.
- :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
- :param \*\*kwargs: Optional arguments that ``request`` takes.
- :return: :class:`Response <Response>` object
- :rtype: requests.Response
复制代码
requests.post方法
- Help on function post in module requests.api:
- post(url, data=None, json=None, **kwargs)
- Sends a POST request.
-
- :param url: URL for the new :class:`Request` object.
- :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
- :param json: (optional) json data to send in the body of the :class:`Request`.
- :param \*\*kwargs: Optional arguments that ``request`` takes.
- :return: :class:`Response <Response>` object
- :rtype: requests.Response
复制代码
|
|