网络爬虫:
网络爬虫(又被称作网络蜘蛛、网络机器人,在某社区中经常被称为网页追逐者),可以按照指定的规则(网络爬虫的算法)自动浏览或抓取网络中的信息,通过Python可以很轻松地编写爬虫程序或者是脚本。
在生活中网络爬虫经常出现,搜索引擎就离不开网络爬虫。例如,百度搜索引擎的爬虫名字叫作百度蜘蛛(Baiduspider)。百度蜘蛛,是百度搜索引擎的一个自动程序。它每天都会在海量的互联网信息中进行爬取,收集并整理互联网上的网页、图片视频等信息。然后当用户在百度搜索引擎中输入对应的关键词时,百度将从收集的网络信息中找出相关的内容,按照一定的顺序将信息展现给用户。百度蜘蛛在工作的过程中,搜索引擎会构建一个调度程序来调度百度蜘蛛的工作,这些调度程序都是需要使用一定的算法来实现的,采用不同的算法,爬虫的工作效率也会有所不同,爬取的结果也会有所差异。
基本原理
Python实现HTTP请求常见的三种方式:urllib,urllib3,requests,其中urllib是Python自带模块,urllib3和requests需要手动安装:
终端输入 pip install requests 进行安装
urllib模块的函数信息
示例程序【NetRequest.py】
import urllib.request import urllib.parse import urllib3 #需要安装包 import requests #在下面的终端输入 pip install requests 进行安装 #打开指定需要爬取的网页 response=urllib.request.urlopen("https://www.baidu.com") html=response.read() print(html) print("----------------------演示post----------------------") data=bytes(urllib.parse.urlencode({"word":"hello"}), encoding='utf8') response=urllib.request.urlopen("http://www.httpbin.org/post",data=data) html=response.read() print(html) print("----------------------使用urllib3库----------------------") http=urllib3.PoolManager() response=http.request('GET',"http://www.baidu.com/") print(response.data) print("----------------------使用requests库----------------------") response=requests.get('http://www.baidu.com/') print("状态码:",response.status_code) print("url地址:",response.url) print("headers头信息:",response.headers) print("cookie信息:",response.cookies) print("文本源码:",response.text) print("字节源码",response.content) #超时时间为5秒,一个不存在的url try: response=requests.post("http://www.xyzsnake.com/post",timeout=5) print("文本:",response.text,",状态码:",response.status_code) except Exception as e: print("异常信息:",str(e))