爬虫之request

目录

  • 爬虫基本流程
  • request和response
    • request
    • response
    • 演示
    • 解析方式
      • requests库
    • 基本get请求
      • 1. 基本写法
      • 2. 带参数get请求
      • 3. 解析json
      • 4. 获取二进制数据
      • 5. 添加headers
    • 基本post请求
    • 响应
    • 状态码判断:
    • 高级操作
  • beautifulsoup库
  • 爬取汽车之家示例

爬虫基本流程

  1. 发起请求:通过http库向目标站点发起请求,即发送一个request,请求可以包含额外的headers等信息,等待服务器相应
  2. 获取相应内容:如果服务器能正常相应,会得到一个response,response的内容便是所要获取的页面内容,类型可能有HTML,json字符串,二进制数据(如图片视频)等类型
  3. 解析内容:得到的内容可能是HTML,可以用正则表达式,网页解析库进行解析,可能是json,可以直接转为json对象,可能是二进制数据,可以做保存或者进一步的处理
  4. 保存数据:可以存为文本,也可以保存至数据库,或者特定格式的文件

request和response

  1. 浏览器发送消息给该网址所在的服务器,叫http request
  2. 服务器收到浏览器发送的消息后,能够根据浏览器发送消息的内容,做相应处理,然后把消息回传给浏览器,叫http response
  3. 浏览器收到服务器的response信息后,对信息进行相应处理,然后展示

request

请求方式有get,post两种,另外还有head,put,delete,options等
请求URL,全球统一资源定位符,任何一个网页图片文档等,都可以用URL唯一确定
请求头,包含请求时的头部信息,如user-agent,host,cookies等
请求体,请求时额外携带的数据,如表单提交时的表单数据

response

响应状态,有多种相应状态200成功,301跳转,404找不到页面,502服务器错误
响应头,如内容类型,内容长度吗,服务器信息,设置cookies等
响应体,最主要的部分,包括了请求资源的内容,如网页HTML,图片,二进制数据等

演示

import requests    # 网页uheaders = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}
response = requests.get('http://www.baidu.com', headers=uheaders)
print(response.text)
print(response.headers)
print(response.status_code)response = requests.get('https://www.baidu.com/img/baidu_jgylogo3.gif')    # 图片
res = response.content
with open('1.gif','wb') as f:f.write(res)

解析方式

直接处理
json解析
正则表达式
beautifulsoup
pyquery
xpath

requests库

各种请求方法

import requestsrequests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')

基本get请求

1. 基本写法

import requestsresponse=requests.get('http://httpbin.org/get')
print(response.text){"args": {}, "headers": {"Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "httpbin.org", "User-Agent": "python-requests/2.19.1"}, "origin": "115.214.23.142", "url": "http://httpbin.org/get"
}

2. 带参数get请求

import requestsresponse=requests.get('http://httpbin.org/get?name=germey&age=22')
print(response.text)data={'name':'germey','age':22}
response=requests.get('http://httpbin.org/get',params=data){"args": {"age": "22", "name": "germey"}, "headers": {"Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "httpbin.org", "User-Agent": "python-requests/2.19.1"}, "origin": "115.214.23.142", "url": "http://httpbin.org/get?name=germey&age=22"
}

3. 解析json

import requestsresponse=requests.get('http://httpbin.org/get')
print(type(response.text))
print(response.json())
print(type(response.json()))<class 'str'>
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.19.1'}, 'origin': '115.214.23.142', 'url': 'http://httpbin.org/get'}
<class 'dict'>

4. 获取二进制数据

import requestsresponse=requests.get('http://github.com/favicon.ico')
with open() as f:f.write(response.content)

5. 添加headers

import requestsheaders={'User-Agent':''}
response=requests.get('http://www.zhihu.com/explore',headers=headers)
print(response.text)

基本post请求

import requestsdata={'name':'germey','age':22}
headers={'User-Agent':''}
response=requests.post('http://httpbin.org/post',data=data,headers=headers)
print(response.json()){'args': {}, 'data': '', 'files': {}, 'form': {'age': '22', 'name': 'germey'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Content-Length': '18', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': ''}, 'json': None, 'origin': '115.214.23.142', 'url': 'http://httpbin.org/post'}

响应

response属性

import requestsresponse = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code)
print(type(response.headers), response.headers)
print(type(response.cookies), response.cookies)
print(type(response.url), response.url)
print(type(response.history), response.history)<class 'int'> 403
<class 'requests.structures.CaseInsensitiveDict'> {'Date': 'Wed, 31 Oct 2018 06:25:29 GMT', 'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Server': 'Tengine', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Content-Encoding': 'gzip', 'X-Via': '1.1 dianxinxiazai180:5 (Cdn Cache Server V2.0), 1.1 PSzjjxdx10wx178:11 (Cdn Cache Server V2.0)'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[]>
<class 'str'> https://www.jianshu.com/
<class 'list'> [<Response [301]>]

状态码判断:

好多种

高级操作

文件上传

import requestsfiles={'file':open('1.jpg','rb')}
response=requests.post('http://httpbin.org/post',files=files)
print(response.text)

获取cookie

import requestsresponse=requests.get('http://www.baidu.com')
print(response.cookies)
for key,value in response.cookies.items():print(key+'='+value)<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315

会话维持

import requestss=requests.Session()
s.get('http://httpbin.org/cookies/set/number/123456789')
response=s.get('http://httpbin.org/cookies')
print(response.text){"cookies": {"number": "123456789"}}

证书验证

代理设置

超时设置

import requests
from requests.exceptions import ReadTimeout
try:response=requests.get('https://www.taobao.com',timeout= 1)print(response.status_code)
except ReadTimeout:print('Timeout')

认证设置

import requestsr = requests.get('', auth=('user', '123'))
print(r.status_code)

异常处理

import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException
try:response=requests.get('http://httpbin.org/get',timeout=0.5)print(response.status_code)
except ReadTimeout:print('Timeout')
except ConnectionError:print('connect error')
except RequestException:print('Error')

beautifulsoup库

爬取汽车之家示例

import requests # 伪造浏览器发起Http请求
from bs4 import BeautifulSoup # 将html格式的字符串解析成对象,对象.find/find__allresponse = requests.get('https://www.autohome.com.cn/news/')
response.encoding = 'gbk'  # 网站是gbk编码的
soup = BeautifulSoup(response.text, 'html.parser')
div = soup.find(name='div', attrs={'id': 'auto-channel-lazyload-article'})
li_list = div.find_all(name='li')
for li in li_list:title = li.find(name='h3')if not title:continuep = li.find(name='p')a = li.find(name='a')print(title.text)  # 标题print(a.attrs.get('href'))  # 标题链接,取属性值,字典形式print(p.text)  # 摘要img = li.find(name='img')  # 图片src = img.get('src')src = 'https:' + srcprint(src)file_name = src.rsplit('/', maxsplit=1)[1]ret = requests.get(src)with open(file_name, 'wb') as f:f.write(ret.content)  # 二进制

转载于:https://www.cnblogs.com/qiuyicheng/p/10753117.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/411638.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

工作379-回调日期补0操作

var data econsole.log(this.continuousDays, "continuousDays")data data.setDate(data.getDate() this.continuousDays);data new Date(e);console.log(data, "data")let dateYear1 data.getFullYear(); //获取年console.log(dateYear1, "date…

征途pak文件修改_传奇技能,第十四祭:装备属性修改与增加新装备

技能献祭&#xff0c;Get 新技能&#xff1a;传奇技能——应用篇&#xff0c;增加新装备与绑特效跟航家学技能&#xff0c;用正式服带你飞&#xff0c;底部有配套学习资源场景&#xff1a;游戏中装备的属性是可以修改的&#xff0c;基础攻防属性可以直接在物品数据库中修改&…

8月18日 小雨

小爱&#xff0c;昨天你睡的很可爱 呵呵 我今天没晚&#xff0c;居然提前20分钟自己醒了。 刚来公司&#xff0c;就收到经理通知&#xff0c;中午大家要去开发区吃饭&#xff0c;下午事都处理完就可能放假&#xff0c;HOHO。 提前告诉小爱&#xff0c;不要着急。 我爱你 转载于…

python tornado对接权限中心的sdk封装

# -*- coding: utf-8 -*- import jsonimport requests import logging as loggerfrom python.akskapp.scripts.api.baseHandler import Rclass AuthSdk(object):# 登录def loginToAuthcenter(self, username, password):resp Noneheaders {"Content-Type": "a…

mysql事务模式怎么查_Mysql InnoDB中的查询事务模式与锁定select ..for update

在 InnoDB 的行锁中使用所谓的 next-key locking。这就意味着&#xff0c;除了索引记录外&#xff0c;InnoDB 还可以锁定该索引记录前部“间隙” (gap) 以阻塞其它用户在索引记录前部的直接插入。next-key lock 意思是锁定一个索引记录以及该记录之前的间隙(gap)。gap lock 就是…

[jQuery] jQuery中如何将数组转化为json字符串,然后再转化回来?

[jQuery] jQuery中如何将数组转化为json字符串&#xff0c;然后再转化回来&#xff1f; var typeOf obj > Object.prototype.toString.call(obj); typeOf([1]); // "[object Array]" typeOf($([1])); // "[object Object]" $([1]).toArray();个人简…

.NET反射、委托技术与设计模式

转自&#xff1a;http://hi.baidu.com/nanashitou/blog/item/ad7346eed769ffffb2fb958a.html 1 反射技术与设计模式 反射&#xff08;Reflection&#xff09;是.NET中的重要机制&#xff0c;通过放射&#xff0c;可以在运行时获得.NET中每一个类型&#xff08;包括类、…

python之yield的一些应用

生成器 yield是用于生成器。生成器通俗的认为&#xff0c;在一个函数中&#xff0c;使用了yield来代替return的位置的函数&#xff0c;就是生成器。它不同于函数的使用方法是&#xff1a;函数使用return来进行返回值&#xff0c;每调用一次&#xff0c;返回一个新加工好的数据返…

本题要求实现一个用选择法对整数数组进行简单排序的函数。_通俗易懂讲 Python 算法:快速排序...

原文&#xff1a;https://stackabuse.com/quicksort-in-python/作者&#xff1a;Marcus Sanatan译者&#xff1a;老齐欢迎在 bilibili 搜索 freeCodeCamp 官方账号或者直接访问 https://space.bilibili.com/335505768 观看我们的技术视频介绍快速排序是一种流行的排序算法&…

[jQuery]JQuery一个对象可以同时绑定多个事件,这是如何实现的?

JQuery一个对象可以同时绑定多个事件&#xff0c;这是如何实现的&#xff1f; ①$(document).ready(function() {$("button").bind({click: function() {$("p").slideToggle()},mouseover: function() {$("body").css("background-color&q…

张娟娟(为奥运冠军名字作诗)

张娟娟&#xff08;为奥运冠军名字作诗&#xff09;——代腾飞 2008年8月18日 于成都张弓搭箭射靶心娟娟俊美胜古今娟弓即破他人梦百步穿杨改乾坤 转载于:https://www.cnblogs.com/daitengfei/archive/2008/08/25/1276023.html

IO_ADDRESS()的实现【转】

上面我们说了如何去在系统中自己实现一个设置系统寄存器的一个方法&#xff0c;上面归根到底要进行物理地址到虚拟地址的映射 现在我们就说说IO_ADDRESS()的实现 #define __REG32ALI&#xff08;addr) (*((volatile unsigned long *)((addr) - ALI_REGS_PHYS_BASE ALI_REGS_V…

vscode标记_高效扩展工具让 VS Code 如虎添翼

Codelf 变量命名神器Star&#xff1a;10688https://github.com/unbug/codelf新建项目&#xff0c;变量&#xff0c;类&#xff0c;方法&#xff0c;接口都需要命名&#xff0c;一个好的命名可以一眼看出这个地方的功能&#xff0c;CodeIf 一键起名不再难&#xff0c;输入关键词…

[html] 如何实现标题栏闪烁、滚动的效果

[html] 如何实现标题栏闪烁、滚动的效果 定时器背景设置个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣一起通关前端面试题

各种数据库连接字符串

1、ACCESS数据库连接set conn Server.CreateObject("ADODB.Connection")conn.Open("driver{Microsoft Access Driver (*.mdb)};dbq" &_Server.MapPath("person.mdb"))set rs conn.Execute( "SELECT * FROM grade" )For I 0 to …

linux服务器情况

查看Linux 进程命令 ps -aux 或者ps -ef linux 进程很多 如果需要查找某一个进程可以使用 管道和grep命令 Linux下常用命令 grep 匹配字符 ps 查询Linux进程 1.查看服务器CPU飙升卡爆&#xff0c;最后发现是服务器在跑挖矿程序&#xff0c;CPU使用率奇高。在此总结…

[html] 页面导入样式时,使用link和@import有什么区别?

[html] 页面导入样式时&#xff0c;使用link和import有什么区别&#xff1f; 区别&#xff1a; 1.link是HTML标签&#xff0c;import是css提供的。 2.link引入的样式页面加载时同时加载&#xff0c;import引入的样式需等页面加载完成后再加载。 3.link没有兼容性问题&#xff…

CSS 有关Position = absolute (绝对定位 是相对于谁而言)

css中有绝对定位法&#xff0c;以前一直搞不懂绝对定位是相对于谁而言的绝对定位。 现在搞清楚了&#xff0c;不是相对于父元素&#xff0c;也不是相对于BODY。 而是相对于所属元素树中&#xff0c;相邻最近的那个显示标识了position属性的元素。 比如 Code<div id"a&q…

[html] 简述超链接target属性的取值和作用

[html] 简述超链接target属性的取值和作用 _self: 在当前窗口打开页面 _blank: 在新窗口打开页面 _top: 在整个框架打开页面不是很理解个人简介 我是歌谣&#xff0c;欢迎和大家一起交流前后端知识。放弃很容易&#xff0c; 但坚持一定很酷。欢迎大家一起讨论 主目录 与歌谣…

mysql gui vim_vim(一): 小技巧

1) 如何yank字符然后再查找 ( / Ctrl - R 0 ) The most recently yanked text will be stored in the 0 and registers (if no register was explicitly specified e.g. by xy ). Then you can paste the text of any that register in the last line (eith1) 如何yank字符然后…