目录

  • 爬虫基本流程
  • 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

爬虫之request相关推荐

  1. 爬虫进行request请求时User-Agent怎样写

    场景 在写爬虫进行request请求时,如果不能正常请求就要添加请求头. 常用的是修改User-Agent来伪装浏览器. 我们除了复制之外,这里可以参照一个库叫fake-useragent. 网址: ...

  2. python爬虫模块_Python爬虫(request模块)

    Python Python开发 Python语言 Python爬虫(request模块) 发送简单的请求: 发送带header的请求: 发送带参数的请求: 例子如下: import requests ...

  3. python request库_【Python爬虫】Request库入门

    什么是爬虫? 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引. ...

  4. 【Python爬虫】Request库入门

    什么是爬虫? 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本.另外一些不常使用的名字还有蚂蚁.自动索引. ...

  5. Python爬虫-02 request模块爬取妹子图网站

    简介 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3)#注意:requests库发送请求将网页内容下载 ...

  6. python爬虫之request.get()参数

    文章目录 前情回顾 目前反爬总结 请求模块总结 解析模块总结 xpath表达式 增量爬虫如何实现 Chrome浏览器安装插件 今日笔记 链家二手房案例(xpath) 百度贴吧图片抓取 requests ...

  7. 爬虫之request模块

    目录 request模块理论 实战练习 1.需求:爬取搜狗首页的页面数据 2.需求:爬取搜狗指定词条对应的搜索结果页面(简易网页采集器) 3.需求:破解百度翻译 4.爬取肯德基地点 5.爬取国家药品监 ...

  8. 我的第一个爬虫:request+pyquery爬取B站热门视频标题与播放量

    爬虫步骤 发起请求: 获取响应内容: 解析内容: 保存数据. 具体实现 在写爬虫之前,我们先来看一下要爬取的网页. 上图是B站热门视频排行榜,需要的数据已经在图中标出,即视频名称和播放量. 接下来是具 ...

  9. 用Python爬虫的request方式实现自动签到

    人生苦短,快学Python! 大家好,我是朱小五.之前我曾经写过一个Python改变生活系列的文章,介绍自己如何使用Python解决了各种各样的日常需求.在这其中有一篇文章<Python改变生活 ...

最新文章

  1. 如何在Git中更改多次提交的作者和提交者名称以及电子邮件?
  2. 移动app部分机型无法唤起h5支付宝支付_案例分析:H5支付交互体验设计
  3. 手机长时间不用自动断网_不用蓝牙的感应音箱,只需百元!放上手机自动播放,媲美千元音质...
  4. zedboard--zynq使用自带外设IP让ARM PS访问FPGA(八) 转载
  5. ibatis 数据库获取不到 java_如何拦截ibatis中所有的执行sql,并记录进数据库
  6. appnode php,环境软件路径参考
  7. ireport怎么套打_DNF小小王国历险记巨人击退战怎么打 巨人击退战通关技巧攻略...
  8. python设置二维列表_Python设置为列表
  9. 并发编程 进程基础
  10. 【腾讯犀牛鸟开源人才培养计划】开源人才培养计划活动参与指南
  11. JAVA JSP学生助学金管理系统 jsp学生资助管理系统jsp学生管理系统jsp贷款管理系统jsp大学生贷款管理系统
  12. C语言课设贪吃蛇说明书,c语言课设贪吃蛇.doc
  13. 《暗时间》读书笔记及读后感
  14. 【调剂】上海应用技术大学2021年硕士研究生招生考试调剂信息
  15. 《东周列国志》第五十四回 荀林父纵属亡师 孟侏儒托优悟主
  16. RNA 23. SCI文章中表达基因Cox模型的风险因子关联图(ggrisk)
  17. JAVA基础之单例模式
  18. java xml 大文件怎么打开_JAVA xml 流方式读取。数据挖掘大文件预处理。
  19. 成功搭建Selenium运行环境,能够使用Chrome浏览器打开任意网页
  20. 服务器 战地4 无限载入,战地4卡在loading界面无限载入的解决方法_快吧单机游戏...

热门文章

  1. 王道操作系统考研笔记——2.2.0 交互式系统调度算法
  2. jsp文件通常用common_springboot还能这样用redis
  3. XState Viz 可视化和调试状态机
  4. Java跳出多重循环
  5. vector, list, map在遍历时删除符合条件的元素
  6. 安防监控系统CIF、D1等格式的解释
  7. 当按下ESC键时,关闭应用程序
  8. [react] 说说你是怎么理解react的业务组件和技术组件的?
  9. [html] 进入编辑页面时,如何把光标聚焦到第一个input?
  10. PS教程第二课:PS安装