python初学者笔记——爬虫requests
声明:
内容主要来自于中国大学MOOC上“Python网络爬虫和信息提取”这个视频。文章仅为个人学习记录笔记,如有侵权,或者其他问题,可以及时联系我,我会删除的。
一、Requests库七个主要方法
方法 | 说明 |
---|---|
requests.request() | 构造一个请求,支撑以下各方法的基础方法 |
requests.get() | 获取HTML网页的主要方法,对应HTTP的GET |
requests.head() | 获取HTML网页头信息的方法,对应HTTP的HEAD |
requests.post() | 向HTML网页提交POST请求的方法,对应HTTP的POST |
requests.put() | 向HTML网页提交PUT请求的方法,对应HTTP的PUT |
requests.patch() | 向HTML网页提交局部修改的请求,对应HTTP的PATCH |
requests.delete() | 向HTML网页提交删除请求,对应HTTP的DELETE |
二、get()方法
# 基本格式 r = requests.get(url)
r包含的就是我们get(爬取)的信息,url就是网址。
# 具体格式 r = requests.get(url,params=None,**kwargs)
- params是url中的额外参数,字典或字节流格式,可选。((╯#-_-)╯不懂)。
- **kwargs是12个控制访问的参数。((╯#-_-)╯不懂+1)
三、返回对象的内容
我们爬取的信息(也就是上文中的r),包含了以下几个基础的内容。
属性 | 说明 |
---|---|
r.status_code | HTTP请求的返回状态,200表示链接成功,其他表示失败 |
r.text | HTTP响应内容的字符串形式,即url对应的内容,也就是我们最想得到的信息 |
r.encoding | 从header中猜测的响应内容编码方式 |
r.apparent_encoding | 从内容中分析出的响应内容编码方式 |
r.content | HTTP响应内容的二进制形式 |
简单试下百度:
>>> import requests >>> r = requests.get('http://www.baidu.com') >>> r.status_code 200 >>> r.encoding 'ISO-8859-1' >>> r.text[:1000] '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç\x99¾åº¦ä¸\x80ä¸\x8bï¼\x8cä½\xa0å°±ç\x9f¥é\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input ty' >>> r.apparent_encoding 'utf-8' >>> r.encoding = r.apparent_encoding >>> r.text[:1000] '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su va' >>>
status_code是200,看起来成功了。不过从头文件读取的编码是’ISO-8859-1’格式,text一下,显然看不懂,我们用apparent_encoding换一下,果然……还是看不懂,不过好歹“百度一下,你就知道”能看懂。
【有个错误,后面才看到。如果header头文件中不存在charset,则认为编码为’ISO-8859-1’格式。所以说百度可能没有charset,才导致我们encoding编码是’ISO-8859-1’格式。】
四、实例
视频中还有对requests库主要方法的讲解,不过我觉得实践才是真理,以后用到再说,先爬为敬🐶。
(1) 京东商品页面的爬取
首先我们打开京东网页,随便点击一个商品的链接,进入商品页面。
我这儿随便选了个,我们把商品的网址,也就是URL复制下来。输入程序。
>>> import requests # 导入requests库 >>> url = "https://item.jd.com/1637948875.html" # 输入网址 >>> r = requests.get(url) # 爬取网页 >>> r.status_code # 查看是否正确 200 >>> r.text[:1000] # 输出结果 '<!DOCTYPE HTML>\n<html lang="zh-CN">\n<head>\n <!-- shouji -->\n <meta http-equiv="Content-Type" content="text/html; charset=gbk" />\n <title>匡威(Converse) 匡威官方 经典款 休闲男女帆布鞋 情侣鞋 101010 海军蓝/102307 35/3【图片 价格 品牌 报价】-京东</title>\n <meta name="keywords" content="匡威(Converse) 匡威官方 经典款 休闲男女帆布鞋 情侣鞋 101010 海军蓝/102307 35/3,匡威(Converse),,京东,网上购物"/>\n <meta name="description" content="匡威(Converse) 匡威官方 经典款 休闲男女帆布鞋 情侣鞋 101010 海军蓝/102307 35/3图片、价格、品牌样样齐全!【京东正品行货,全国配送,心动不如行动,立即购买享受更多优惠哦!】" />\n <meta name="format-detection" content="telephone=no">\n <meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/1637948875.html">\n <meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/1637948875.html">\n <meta http-equiv="X-UA-Compatible" content="IE=Edge">\n <link rel="canonical" href="//item.jd.com/1637948875.html"/>\n <link rel="dns-prefetch" href="//misc.360buyimg.com"/>\n <link rel="dns-prefetch" href="//static.360buyimg.com'
圆满成功!!容我吃顿火锅庆祝下!
好了,继续。上面的只是交互模式下的尝试,还需要规范化一些。下面附上全代码:
import requests url = "https://item.jd.com/1637948875.html" try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding print(r.text[:1000]) except: print("爬取失败!!!")
(2)亚马逊商品页面的爬取
同上操作:
import requests >>> url = "https://www.amazon.cn/dp/B01HIUTIO8/ref=sr_1_1?pf_rd_i=1478512071&pf_rd_m=A1U5RCOVU0NYF2&pf_rd_p=c34ba49d-561d-46bc-8df5-4e0f8ddd3dc3&pf_rd_r=RJZ3RH5DVZB0ACD15KY2&pf_rd_s=merchandised-search-top-1&pf_rd_t=101&qid=1574945335&s=gifts&sr=1-1" >>> r = requests .get(url) >>> r.status_code 503 >>> r.encoding = r.apparent_encoding >>> r.text #此处仅截取结果一部分 <p class="a-last">抱歉,我们只是想确认一下当前访问者并非自动程序。为了达到最佳效果,请确保您浏览器上的 Cookie 已启用。</p>\n
哦,天哪,竟然失败了。不要紧,帅气的嵩
天老师(视频的讲解老师)告诉我们,这是因为我们爬虫程序被亚马逊网站识别了,不给我们爬取了。所以我们需要“善意”的告诉他,我们不是爬虫~~~]
>>> r.request.headers # 续上一段代码,这个代码可以看到爬虫信息 {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} # 现在我们需要改一下'User-Agent' >>>tou = {'user-agent':'Mozilla/5.0'} # Mozilla是浏览器的常用头 >>> r = requests.get(url,headers = tou) >>> r.status_code 200 >>> r.encoding = r.apparent_encoding >>> r.text
看,成功了,status_code是200了。然而我输出后,还是需要输入字符。555~看来亚马逊还是能识别我的爬虫。毕竟这个视频是去年的,亚马逊可能升级了。不过我们还是可以从这儿学到,当我们爬虫失败的时候,我们可以尝试改变头,也就是’user-agent’来蒙蔽网站的服务器。下面附上全代码。
import requests url = "亚马逊网址" try: tou = {'user-agent':'Mozilla/5.0'} r = requests.get(url,headers=tou) r.raise_for_status() r.encoding = r.apparent_encoding print(r.text[:1000]) except: print("爬取失败!!!")
实际上,我前几天试过,是成功的,甚至有一次没改user-agent就爬取了页面,不知道为什么今天尝试又失败了。可能是商品链接问题,或者我的ip问题。
好累,不写了,过几天再续。
- 点赞
- 收藏
- 分享
- 文章举报
- Python学习笔记之利用Requests和Lxml实现简单爬虫
- Python爬虫学习纪要(八):Requests 库学习笔记3
- Python爬虫学习纪要(十):Requests 库学习笔记5
- python初学者学习笔记(一)简单的爬虫
- Python爬虫之个人笔记(二):requests模块应用,发送get/post请求,获取响应
- Python爬虫学习纪要(九):Requests 库学习笔记4
- 【python爬虫学习笔记】05 利用requests-bs4的大学排名定向爬虫的实例
- python笔记 爬虫精进·第0课 【初识爬虫,爬虫库requests,requests.get(),status_code,content,encoding】
- 【极客学院】-python学习笔记-3-单线程爬虫 (request安装遇到问题及解决,应用requests提取信息)
- Python爬虫库学习笔记-requests
- Python爬虫初学者学习笔记(带注释)
- Python 爬虫学习笔记一: requests 模块
- python爬虫学习笔记-requests用法
- Python爬虫(入门+进阶)学习笔记 1-3 使用Requests爬取豆瓣短评
- Python爬虫学习纪要(六):Requests 库学习笔记1
- python爬虫之正则表达式学习笔记一
- Python初学者笔记之——字符编码与字符串
- [Python]网络爬虫1:抓取网页的含义和URL基本构成 笔记
- Python简单爬虫开发的学习笔记整理(爬取百度百科词条)
- python学习笔记之网络爬虫(七)爬取官网信息标题