python爬虫---requests库
#encoding: utf-8 import requests #发送get请求: response = requests.get("http://www.baidu.com") #response的一些属性: #查看响应内容。response.text返回的是Unicode格式的数据 print(response.text) #查看响应内容,response.text返回的是Unicode格式的数据 print(response.content) #查看完整url地址 print(response.url) #查看响应头部字符编码 print(response.encoding) #查看响应码 print(response.status_code) """ response.text和response.content的区别: 1.response.content:这个是直接从网络上面抓取的数据。没有经过 任何解码。所以是一个bytes类型。其实在硬盘上和网络上传输的字符串 都是bytes类型。 2.response.text:这个是str的数据类型,是requests库将response.content 进行解码的字符串。解码需要指定一个编码方式,requests会根据自己的猜测 来判断编码的方式。所以有时候可能会猜测错误,就会导致解码产生乱码。这时候就应该 使用'response.content.decode('utf-8')'进行手动解码。 """ #实例如下: params = { 'wd':'中国' } headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36' } response = requests.get("https://www.baidu.com/s",params=params,headers=headers) with open('baidu.html','w',encoding='utf-8') as fp: fp.write(response.content.decode('utf-8')) print(response.url)
import requests """ 发送POST请求: 发送post请求非常简单。直接调用'requests.post'方法就可以。 如果返回的是json数据。那么可以调用'respone.json()' 来将json字符串转化为字典或者列表 """ url = "https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false" data = { 'first':'true', 'pn':'1', 'kd':'python' } headers = { 'Referer':'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36' } response = requests.post(url=url,data=data,headers=headers) # print(response.text) print(response.json())
#使用代理
#在请求方法中,传递'proxies'参数就行了
import requests proxy = { 'http':'183.129.207.80:12655' } response = requests.get("http://httpbin.org/ip",proxies=proxy) print(response.text)
import requests ''' 如果想要在多次请求中共享cookie,那么应该使用session。 实例代码如下: ''' url = "http://www.renren.com/PLogin.do" data = { 'email':"1203244881@qq.cmo", 'password':'woaini1111' } headers = { 'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36" } session = requests.Session() session.post(url,data=data,headers=headers) response = session.get('http://www.renren.com/880151247/profile') with open('renren.html','w',encoding='utf-8') as fp: fp.write(response.text) #处理不信任的SSL证书: resp = requests.get('http://www.12306.cn/mormhweb/',verify=False) print(resp.content.decode('utf-8'))

浙公网安备 33010602011771号