爬虫学习笔记1---------requests库

Unit 1 : Requests库入门 (7 * 13)

 

(1)、安装 pip install requests

 

     测试

import requests

r = requests.get("http://www.baidu.com")

r.status_code

     200

r.encoding = 'utf-8'

r.text     #打印内容

 

 

(2)、request库的7个主要方法对应HTTP的7个方法

 

  •      requests.request()     构造一个请求,基础方法

               requests.request(method,url,**kwargs)

               method:请求方法,对应get/put/post等7种

               url

               **kwargs,13个控制访问参数:

 

#1、params:字典或字节序列,能增加到URL链接里

kv = {'key1': 'value1','key2':'value2'}

r = requests.request('GET','http://python123.io/ws', params=kv)

print(r.url)

#http://python123.io/ws?key1=value1&key2=value2

 

#2、data:字典、字节序列或文件对象,作为Request的内容

kv = {'key1': 'value1','key2':'value2'}

r = requests.request('POST','http://httpbin.org/post', data = kv)

data值为字典 则存于网页请求的form表单中

body = '主体内容'

r = requests.request('POST','http://httpbin.org/post', data = body)

data值若为字符串  则存于网页请求的data标签中

 

#3、json:JSON格式的数据,作为Request的内容

kv = {'key1': 'value1','key2':'value2'}

r = requests.request('POST','http://httpbin.org/post', json = kv)

 

#4、headers:字典,HTTP定制头,模拟任何浏览器

hd = {'user-agent:'Chrome/10'}

r = requests.request('POST','http://httpbin.org/post', headers = hd)

 

##高级功能:

#5、cookies:字典或CookieJar,Request中的cookie

#6、auth:元组,支持HTTP认证功能

 

#7、file:字典类型,传输文件

fs = {'file':open('data.xls','rb')}

r = requests.request('POST','http://python123.io/ws',files=fs)

 

#8、timeout:设定超时时间,秒为单位

r = reqquests.request('GET','http://www.baidu.com', timeout=10)

 

#9、proxies:字典类型,设定访问代理服务器,可以增加登录认证,隐藏用户原IP地址信息,有效的防止对爬虫的逆追踪。

pxs = {'http':'http://user:pass@10.10.10.1:1234','https':'https://10.10.10.1:4321'}

r = requests.request('GET','http://www.baidu.com',proxies=pxs)

 

##高级功能开关

#10、allow_redirects: True/False,默认为True,重定向的开关

#11、stream:True/False,默认为True,获取立即下载的开关

#12、verify:True/Falsse,默认为True,认证SSL证书的开关

 

#13、cert:本地SSL证书路径

 

  •      requests.get()        最常用,获取HTML网页,对应HTTP的GET,其它受限

r = requests.get(url) # .get()构造 Request对象

#返回 Response对象 r

requests.get(url,params=None,**kwargs)

#源码都是调用了request方法

 

##Response对象

import requests

r = requests.get("http://www.baidu.com")

print(r.status_code) #200

type(r)

r.text

r.encoding     #charset字段,如果header中不存在charset,则认为编码为ISO-8859-1

r.apparent_encoding

#替换编码方式

r.encoding = "utf-8"

r.text

r.headers

Response对象的属性

     r.status_code     返回状态,200成功,404……失败

     r.text     字符串形式的页面内容

     r.encoding     从HTTP header 中猜测的响应内容编码方式

     r.apparent_encoding     从内容文本中分析的编码方式(备选编码方式)

     r.content     HTTP响应内容的二进制形式

 

  •     requests.head()     获取HTML网页头,对应HTTP的HEAD

          requests.head(url, **kwargs)

 

  •     requests.post()     向HTML网页提交POST请求,对应HTTP的POST

          requests.post(url, data=None, json=None, **kwargs)

 

     向URL追加一个字典:

 

payload = {'key1': 'value1','key2':'value2'}

r = requests.post('http://httpbin.org/post',data = payload)

print(r.text) #向url POST一个字典,自动编码为"form"(表单)

 

     向URL追加一个data:

r = requests.post('http://httpbin.org/post',data = "ABC")

print(r.text) #向url POST,自动编码为data,"data"="ABC"

 

  •     requests.put()         向HTML网页提交PUT请求,对应HTTP的PUT

可覆盖原有数据

          requests.put(url, data=None, **kwargs)

 

  •     requests.patch()     向HTML网页提交局部修改请求,对应HTTP的PATCH

          requests.patch(url, data=None, **kwargs)

 

  •     requests.delete()     向HTML网页提交删除请求,对应HTTP的DELETE

          requests.delete(url, **kwargs)

 

(3)、爬取网页的通用代码框架

 

Request库异常处理

  • requests.ConnectionError    网络连接错误异常,如DNS查询失败、防火墙拒绝连接等
  • requests.HTTPError    HTTP协议层面错误异常
  • requests.URLRequired   URL缺失异常
  • requests.TooManyRedirects    超过最大重定向次数,产生重定向异常,复杂连接
  • requests.ConnectTimeout    连接远程服务器超时异常
  • requests.Timeout    请求URL超时

理解Requests库的异常

r.raise_for_status()    如果不是200,产生异常requests.HTTPError

 

#通用代码框架

 

import requests

def getHTMLText(url):

     try:

          r = requests.get(url, timeout=30)

          r.raise_for_status() #如果状态不是200,引发HTTPError异常

          r.encoding = r.apparent_encoding

          return r.text

     except:

          return "产生异常"

#测试

if __name__ == "__main__":

     url = "http://www.baidu.com"

     print(getHTMLText(url))

 

(4)、HTTP协议

     HTTP,Hypertext Tranfer Protocol,超文本传输协议,是一个基于"请求与响应"模式的、无状态(前后响应没有关系)的应用层(工作在TCP协议之上)协议。

     一般采用URL作为定位网络资源的标识。

     URL格式     http://host[:port][path]

  • host:合法的Internet主机域名或IP地址
  • port:端口号,缺省为80
  • path:请求资源的路径

     URL的理解:

     URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源。

          HTTP协议对资源的操作,方法:

  • GET    请求获取URL位置的资源
  • HEAD   请求获取URL位置资源的响应消息报告,获得头部信息
  • POST   请求向URL位置的资源后附加新的数据(追加)
  • PUT    请求向URL位置储存一个资源 (覆盖)
  • PATCH   改变该资源处部分内容 (修改)
  • DELETE   删除该位置储存的资源

          PUT与PATCH区别:PATCH只用修改其中一个。

 


 

Unit 2 : 网络爬虫“盗亦有道”

 

网络爬虫尺寸:

 

小规模,数据量小

爬取速度不敏感

Requests库

中规模,数据规模较大,爬取速度敏感

Scrapy库

大规模,搜索引擎

爬取速度关键

定制开发

爬取网页,玩转网页爬取网站,爬取系列网站爬取全网

 

网络爬虫“骚扰”,法律风险(服务器上的数据有产权),个人隐私泄露。

 

网络爬虫的限制

  •     来源审查:判断User-Agent进行限制
    • 检查来访问HTTP协议头的User-Agent域,只响应浏览器或友好爬虫的访问。
  • 发布公告:Robots协议:
    • 告知爬虫策略,要求遵守

 

Robots 协议:在网站根目录下的robots.txt文件。

案例:京东(https://www.jd.com/robots.txt):

 

User-agent: *

Disallow: /?*

Disallow: /pop/*.html

Disallow: /pinpai/*.html?*

User-agent: EtaoSpider

Disallow: /

User-agent: HuihuiSpider

Disallow: /

User-agent: GwdangSpider

Disallow: /

User-agent: WochachaSpider

Disallow: /

 

    #robots基本语法:*代表所有,/代表根目录

        User-agent:*

        Disallow:/

遵守方式:

  • 网络爬虫:自动或人工识别robots.txt,再进行内容爬取。
  • 约束性:可以不遵守,但存在法律风险。

 


 

Unit 3 : Requests库网络爬虫实例

 

一 、京东商品信息爬取

 

import requests

url = "https://item.jd.com/2967929.html"

try:

     r = requests.get(url)

     r.raise_for_status()

     r.encoding = r.apparent_encoding

     print(r.text[:1000])

except:

     print("爬取失败")

 

 

二、亚马逊商品

有反爬虫程序,需要模拟浏览器的headers,添加user-agent:

 

import requests

url = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"

try:

     kv = {'user-agent':'Mozilla/5.0'}

     r = requests.get(url, headers = kv)

     r.raise_for_status()

     r.encoding = r.apparent_encoding

     print(r.text[1000:2000]

except:

     print("爬取失败")

 

 

三、百度/360搜索关键词提交

 

百度的关键词接口:

http://www.baidu.com/s?wd=keyword

 

import requests

url = "http://www.baidu.com/s"

kv = {'wd':'python'}

try:

    r = requests.get(url, params = kv)

    r.raise_for_status ()

    r.encoding = r.apparent_encoding

    print(r.text[2000:4000])

except:

    print(r.url)

    print("爬取失败")

 

360关键字接口:

http://www.so.com/s?q=keyword

 

import requests

url = "http://www.so.com/s"

kv = {'q':'python'}

try:

    r = requests.get(url, params = kv)

    r.raise_for_status ()

    r.encoding = r.apparent_encoding

    print(len(r.text))

except:

    print(r.url)

    print("爬取失败")

 

 

 

四、网络图片的爬取和存储

 

www.nationalgeographic.com.cn/photography/photo_of_the_day/3921.html

 

import requests

import os

url = "http://image.nationalgeographic.com.cn/2017/0211/20170211061910157.jpg"

root = "D://pics//"

path = root + url.split('/')[-1]

try:

    if not os.path.exists(root):

          os.mkdir(root)

    if not os.path.exists(path):

        r = requests.get(url)

        with open(path, 'wb') as f:

            f.write(r.content)

            f.close()

            print("文件保存成功")

    else:

        print("文件已经存在")

except:

    print("爬取失败")

 

五、IP地址归属地的自动查询

 

http://m.ip138.com/ip.asp?ip=ipaddress

import requests

url = "http://m.ip138.com/ip.asp?ip="

try:

    r = requests.get(url + '202.102.111.110')

    r.raise_for_status()

    r.enconding = r.apparent_encoding

    print(r.text[-500:])

except:

    print("爬取失败")

 

 

总结:以爬虫视角看待网络资源,所有对资源的操作都是通过url链接来实现的 。

 

注: 可看慕课或b站上 嵩天老师讲的python网络爬虫与信息提取课程

         本文为视频内容  转载自https://blog.youkuaiyun.com/youyinyou/article/details/77745131

爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求实现,如Python中的Requests。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据、NoSQL数据、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值