1. 网络爬虫

  • 爬虫定义:
    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),
    是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。
    另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。
  • 两大特征
  • 按照作者的要求下载数据和内容
  • 能自动在网络上流窜
  • 三大步骤
  • 下载网页
  • 提取正确的信息
  • 根据一定的规则自动跳到另外的网页执行以上两步内容
  • 爬虫分类
  • 通用爬虫(搜索引擎,类似百度,搜狗)
  • 专用爬虫(聚焦爬虫)
  • Python网络爬虫包介绍
  • Python3.x
  • urllib, urllib3, httplib2, requests
  • 常用组合:urllib, requests

2. urllib包

2.1. 包含模块

  • urllib.request: 打开和读取urls
  • urllib.error: 包含urllib.request产生的常见错误,使用try捕捉
  • urllib.parse: 包含即系url的方法
  • urllib.robotparse: 解析robots.txt文件
  • 查看实例43_1
from urllib import request

if __name__ == '__main__':
url = 'https://guangdiu.com/detail.php?id=6637916'
# 打开一个URL然后返回页面的内容
rsp = request.urlopen(url)
# 把返回的结果读取出来
html = rsp.read()
print(type(html))
# 返回的字节,需要解码
html = html.decode()
print(html)

2.2. 网页编码问题的解决

  • chardet 可以自动检测页面文件的编码格式,但是可能有误
  • 比如上面实例运行后结果开头里面就有:
  • 需要安装chardet包
  • pycharm虚拟环境下安装包,直接进入解释器设置界面,点击包列表右边
  • 的加号,进去搜索所需的包,安装即可
  • 自动检测编码看实例
  • 43_2
import chardet
from urllib import request

if __name__ == '__main__':
url = 'http://china.chinadaily.com.cn/a/201901/15/WS5c3d510fa31010568bdc3902.html'
# 打开一个URL然后返回页面的内容
rsp = request.urlopen(url)
# 把返回的结果读取出来
print(type(rsp))
html = rsp.read()
print(type(html))
# 利用chardet检测编码
# 类型是一个字典,字典中有采用的编码
cs = chardet.detect(html)
print(type(cs))
print(cs)

# 返回的字节,需要解码
# 使用get函数获得不会出错,有自己的编码就用检测到的编码解码
# 如果没有检测到,就采用utf-8解码
html = html.decode(cs.get('encoding', 'utf-8'))
print(html)

下接:
Python3网络爬虫教程2——urlopen的返回对象