python爬虫基础教程:requests库(二)代码实例
Python  /  管理员 发布于 7年前   170
get请求
简单使用
import requests'''想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载!'''response = requests.get("https://www.baidu.com/")#text返回的是unicode的字符串,可能会出现乱码情况# print(response.text) #content返回的是字节,需要解码print(response.content.decode('utf-8')) # print(response.url) #https://www.baidu.com/# print(response.status_code) #200# print(response.encoding) #ISO-8859-1
添加headers和params
import requests params = { 'wd':'python'}headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'} response = requests.get("https://www.baidu.com/s",params=params,headers=headers) #content返回的是字节,需要解码with open('baidu.html','w',encoding='utf-8') as f: f.write(response.content.decode('utf-8'))
POST请求
爬去拉钩网职位信息
import requests url = "https://www.lagou.com/jobs/positionAjax.json?city=%E5%8C%97%E4%BA%AC&needAddtionalResult=false" data = { 'first':'true', 'pn':1, 'kd':'python'} headers = { "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36", "Referer":"https://www.lagou.com/jobs/list_python?city=%E5%8C%97%E4%BA%AC&cl=false&fromSearch=true&labelWords=&suginput="} response = requests.post(url,data=data,headers=headers)# print(response.text)print(type(response.text)) #<class 'str'>print(type(response.json())) #<class 'dict'> print(response.json()) #获取为字典的形式
使用代理
import requests proxy = {'http':'115.210.31.236.55:9000'} response = requests.get("https://www.baidu.com/",proxies=proxy) print(response.content.decode('utf-8'))
session登录
# _*_ coding:utf-8 _*_ import requests # 1. 创建session对象,可以保存Cookie值ssion = requests.session() # 2. 处理 headersheaders = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'} # 3. 需要登录的用户名和密码data = {"email":"158xxxxxxxx", "password":"pythonxxxxxxx"} # 4. 发送附带用户名和密码的请求,并获取登录后的Cookie值,保存在ssion里ssion.post("http://www.renren.com/PLogin.do", data = data) # 5. ssion包含用户登录后的Cookie值,可以直接访问那些登录后才可以访问的页面response = ssion.get("http://zhibo.renren.com/news/108") # 6. 打印响应内容print(response.text)
以上所述是小编给大家介绍的python爬虫基础教程:requests库(二)详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号