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)
  1. params是url中的额外参数,字典或字节流格式,可选。((╯#-_-)╯不懂)。
  2. **kwargs是12个控制访问的参数。((╯#-_-)╯不懂+1)

三、返回对象的内容

我们爬取的信息(也就是上文中的r),包含了以下几个基础的内容。

属性说明
r.status_codeHTTP请求的返回状态,200表示链接成功,其他表示失败
r.textHTTP响应内容的字符串形式,即url对应的内容,也就是我们最想得到的信息
r.encoding从header中猜测的响应内容编码方式
r.apparent_encoding从内容中分析出的响应内容编码方式
r.contentHTTP响应内容的二进制形式

简单试下百度:

>>> 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问题。
好累,不写了,过几天再续。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值