Requests库的get()方法

通过requests.get(url)构造一个向服务器请求资源的Requests对象

r = requests.get(url)

Response对象的属性

Python网络爬虫与信息提取——Requests库的get()方法-米宝教室

Response对象的属性的使用方法

Python网络爬虫与信息提取——Requests库的get()方法-米宝教室
>>> import requests # 载入Requests库
>>> r = requests.get("http://www.baidu.com") # 使用get()访问网页
>>> r.status_code #检测页面是否访问成功,返回200表示访问成功,返回404或其他表示访问不成功
200
>>> r.text # 打印当前页面信息
>>> r.encoding # 从HTTP header猜测的响应内容的编码方式
>>> r.apparent_encoding # 从内容中分析出来的编码方式
>>> r.encoding = 'utf-8' # 将编码方式转为utf-8 编码
Python网络爬虫与信息提取——Requests库的get()方法-米宝教室

爬取网页的通用代码框架

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())