Python爬虫 requests库基础

requests库简介

requests是使用Apache2 licensed 许可证的HTTP库。

用python编写。

比urllib2模块更简洁。

Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和POST数据自动编码。

在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得人性化,使用Requests可以轻而易举的完成浏览器可有的任何操作。

现代,国际化,友好。

requests会自动实现持久连接keep-alive

requests库安装

pip install requests

第一个爬虫程序:爬取搜狗首页的页面数据

import requests
def main():
    #1、指定url
    url='https://www.sogou.com/'
    #2、发起get请求,会返回一个相应对象
    response=requests.get(url=url)
    #3、获取响应数据,调用响应对象的text属性,可获取页面源码数据
    page_text=response.text
    print(page_text)
    #4、进行持久化存储,这里是写入文件,也可以存入数据库
    with open('./sogou.html','w',encoding='utf-8') as fp:
        fp.write(page_text)
    print('爬虫结束!')
if __name__=='__main__':
    main()

这样就可以自动获取到搜狗首页的数据了,下面是部分截图

猜你喜欢

转载自www.cnblogs.com/andrew3/p/12716962.html