requesets库使用

  • Beautiful is better than ugly.(美丽优于丑陋)
  • Explicit is better than implicit.(清楚优于含糊)
  • Simple is better than complex.(简单优于复杂)
  • Complex is better than complicated.(复杂优于繁琐)
  • Readability counts.(重要的是可读性)

requests库中文官网

http://cn.python-requests.org/zh_CN/latest/user/quickstart.html

 

一、导入库

import requests

发送基本的get请求

r = requests.get(url)

使用requests方法后,会返回一个response对象,r就是response对象

Response对象的属性
r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败
r.text HTTP响应内容的字符串形式,即url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式(
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content HTTP响应内容的二进制形式

r.encoding和r.apparent_encoding的区别
r.encoding:如果header中不存在charset,则认为编码为ISO-8859-1
r.apparent_encoding:根据网页内容分析出的编码方式
综上所述,r.apparent_encoding比r.encoding更为准确

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

Robots协议基本语法
User-agent:*
Disallow: /
* 代表所有 , / 代表根目录

 

 

 

爬取网页通用框架

import requests

def getHTMLText(url1):
  try:
    r = requests.get(url1, timeout=30)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    return r.text
  except:
    return "产生异常"

 原文链接:https://blog.csdn.net/dawn___/article/details/64543157

posted @ 2019-08-22 23:47  Whisperbb  阅读(522)  评论(0编辑  收藏  举报