嵩天老师python爬虫笔记整理week1

这篇博客介绍了嵩天老师关于Python爬虫的笔记,主要涵盖Request库的使用,包括GET请求、异常处理、编码问题以及通用代码框架。讨论了网络爬虫的道德规范,如Robots协议,并通过京东、亚马逊等案例进行实战解析。还涉及到了网络图片爬取、IP地址查询等应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Request库入门

首先来看下request的基本使用,基本使用如下

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

  • url : 拟获取页面的url链接

  • params : url中的额外参数,字典或字节流格式,可选

  • **kwargs: 12个控制访问的参数

    import requests
    r=requests.get("http://www.baidu.com")
    print(r.status_code)
    r.text[:400]
    
    200
    '<!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=h'
    

    这里可以看到r.text内容有乱码,这里是编码的问题,后续会处理。

    再来看下r的类型。

    type(r)
    
    requests.model.Response
    

    可以看到r是Response类型的,这里再来看下Response对象的属性

    r.headers
    
    {'Server': 'bfe/1.0.8.18', 'Date': 'Sun, 13 May 2018 02:09:06 GMT', 'Content-Type': 'text/html', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:36 GMT', 'Transfer-Encoding': 'chunked', 'Connection': 'Keep-Alive', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Pragma': 'no-cache', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Content-Encoding': 'gzip'}
    
    r.status_code
    
    200
    

    status_code是状态相应码,如果是200表示正常,否则为异常,所以后续处理的时候要使用try…except

    r.encoding
    
    'ISO-8859-1'
    

encoding从HTTP header中猜测的响应内容编码方式。如果header中不存在charset,则认为编码为ISO‐8859‐1。 r.text根据r.encoding显示网页内容。这也就是为什么之前的内容中有乱码,因为内容里有中文,而编码方式为’ISO-8859-1’。

r.apparent_encoding
'utf-8'

apparent_encoding从内容中分析出的响应内容编码方式(备选编码方式)。根据网页内容分析出的编码方式
可以看作是r.encoding的备选。所以一般处理的时候会让r.encoding=r.apparent_encoding

这里再来看下Request库具体的异常种类。

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

合上述异常处理以及编码问题,这里老师给了一个爬取网页的通用代码框架

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))
<!DOCTYPE html>
<!--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=st
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值