python urllib爬虫模块使用解析


Posted in Python onSeptember 05, 2019

前言

网络爬虫也称为网络蜘蛛、网络机器人,抓取网络的数据。其实就是用Python程序模仿人点击浏览器并访问网站,而且模仿的越逼真越好。一般爬取数据的目的主要是用来做数据分析,或者公司项目做数据测试,公司业务所需数据。

而数据来源可以来自于公司内部数据,第三方平台购买的数据,还可以通过网络爬虫爬取数据。python在网络爬虫方向上有着成熟的请求、解析模块,以及强大的Scrapy网络爬虫框架。

爬虫分类

1、通用网络爬虫:搜索引擎使用,遵守robots协议(君子协议)

robots协议 :网站通过robots协议告诉搜索引擎哪些页面可以抓取,哪些页面不能抓取。https://www.taobao.com/robots.txt

2、聚焦网络爬虫 :自己写的爬虫程序

爬虫爬取数据步骤

  • 确定需要爬取的URL地址
  • 由请求模块向URL地址发出请求,并得到网站的响应
  • 从响应内容中提取所需数据
    • 所需数据,保存
    • 页面中有其他需要继续跟进的URL地址,继续第2步去发请求,如此循环

请求模块

from urllib import request

request.urlopen()

向网站发起请求并获取响应对象

参数:

URL:需要爬取的URL地址

timeout: 设置等待超时时间,指定时间内未得到响应抛出超时异常

响应对象(response)方法

  • string = response.read().decode('utf-8') 获取响应对象内容(网页源代码),返回内容为字节串bytes类型,顺便需要decode转换成string。
  • url = response.geturl() 返回实际数据的URL地址
  • code = response.getcode() 返回HTTP响应码
from urllib import request
url = 'http://www.baidu.com/'

# 向百度发请求,得到响应对象
response = request.urlopen(url)

# 返回网页源代码
print(response.read().decode('utf-8'))

# 返回http响应码
print(response.getcode())    # 200
# 返回实际数据URL地址
print(response.geturl())    # http://www.baidu.com/

urllib.request.Request()

创建请求对象(包装请求,重构User-Agent,使程序更像正常人类请求)

参数

URL:请求的URL地址

headers:添加请求头(爬虫和反爬虫斗争的第一步)

使用流程

1、创建请求对象(重构User-Agent)

req = urllib.request.Request(url=url,headers={'User-Agent':'Mozilla/5.0 xxxx'})

2、请求对象发起请求,获取响应对象(urlopen)

res = urllib.request.urlopen(req)

3、通过相应对象获取响应内容

html = res.read().decode('utf-8')

from urllib import request
url = 'http://httpbin.org/get'
headers = {'User-Agent':'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)'}
# 创建请求对象(包装请求)
req = request.Request(url=url,headers=headers)
# 发请求,获取响应对象
res = request.urlopen(req)
# 读取内容,返回网页代码
html = res.read().decode('utf-8')
print(html)

URL地址编码

urllib.parse.urlencode({dict})

URL地址中一个查询参数

查询参数:{'wd' : '美女'}

urlencode编码后:'wd=%e7%be%8e%e5%a5%b3'

from urllib import parse
url = 'http://www.baidu.com/s?'
query_string = parse.urlencode({'wd':'美女'})
print(query_string)     # wd=%E7%BE%8E%E5%A5%B3
url = url + query_string
# http://www.baidu.com/wd=%E7%BE%8E%E5%A5%B3

URL地址中多个查询参数

from urllib import parse
query_string_dict = {'wd' : '美女',
          'pn' : '50'}
query_string = parse.urlencode(query_string_dict)
url = 'http://www.baidu.com/s?{}'.format(query_string)
print(url)
# http://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3&pn=50

拼接URL地址的3种方式

1、字符串相加

'https://www.baidu.com/s?' + urlencode({'wd':'美女','pn':'50'})

2、字符串格式化(占位符)

'https://www.baidu.com/s?%s' % urlencode({'wd':'美女','pn':'50'})

3、format()方法

'https://www.baidu.com/s?{}'.format(urlencode({'wd':'美女','pn':'50'}))

示例 在百度中输入要搜索的内容,把响应内容保存到本地文件

from urllib import request
from urllib import parse

# 定义常用变量
word = input('请输入搜索内容:')
url = 'http://www.baidu.com/s?'
headers = {'User-Agent':'Mozilla/5.0'}

# url编码,拼接完整URL
query_string = parse.urlencode({'wd':word})
url = url + query_string

# 三步走
req = request.Request(url=url,headers=headers)
res = request.urlopen(req)
html = res.read().decode('utf-8')

filename = '{}.html'.format(word)
with open(filename,'w',encoding='utf-8') as f:
  f.write(html)

urllib.parse.quote(string)编码

from urllib import parse
parse.quote('美女')    # %E7%BE%8E%E5%A5%B3

urllib.parse.unquote(string)解码

from urllib import parse
result = parse.unquote('%E7%BE%8E%E5%A5%B3')
print(result)    # 美女

百度贴吧网页获取

  • 输入贴吧名称
  • 输入起始页
  • 输入终止页
  • 保存到本地文件:第1页.html、第2页.html ...

实现步骤

1、找URL规律

1、不同吧

2、不同页

第1页:http://tieba.baidu.com/f?kw=????&pn=0

第2页:http://tieba.baidu.com/f?kw=????&pn=50

第n页:pn=(n-1)*50

2、获取网页内容

3、保存(本地文件、数据库)

from urllib import request,parse
import time
import random

class BaiduSpider(object):
  def __init__(self):
    self.url = 'http://tieba.baidu.com/f?kw={}&pn={}'
    self.headers = {'User-Agent':'Mozilla/5.0'}

  # 获取响应
  def get_page(self,url):
    req = request.Request(url=url,headers=self.headers)
    res = request.urlopen(req)
    html = res.read().decode('utf-8')
    return html

  # 保存数据
  def write_page(self,filename,html):
    with open(filename,'w') as f:
      f.write(html)

  # 主函数
  def main(self):
    name = input('请输入贴吧名:')
    start = int(input('请输入起始页:'))
    end = int(input('请输入终止页:'))

    # 拼接URL地址,发请求
    for page in range(start,end+1):
      pn = (page-1)*50
      kw = parse.quote(name)     # url编码
      url = self.url.format(kw,pn)
      html = self.get_page(url)    # 获取响应,并保存
      filename = '{}-第{}页.html'.format(name,page)
      self.write_page(filename,html)
      print('第{}页爬取成功'.format(page)) # 提示进度
      time.sleep(random.randint(1,3))   # 控制爬取速度

if __name__ == '__main__':
  spider = BaiduSpider()
  spider.main()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python使用scrapy采集数据时为每个请求随机分配user-agent的方法
Apr 08 Python
Python获取CPU、内存使用率以及网络使用状态代码
Feb 08 Python
python学习入门细节知识点
Mar 29 Python
python实现人人自动回复、抢沙发功能
Jun 08 Python
python之django母板页面的使用
Jul 03 Python
Python如何实现强制数据类型转换
Nov 22 Python
pycharm通过anaconda安装pyqt5的教程
Mar 24 Python
win7上tensorflow2.2.0安装成功 引用DLL load failed时找不到指定模块 tensorflow has no attribute xxx 解决方法
May 20 Python
python filecmp.dircmp实现递归比对两个目录的方法
May 22 Python
Python 解决相对路径问题:"No such file or directory"
Jun 05 Python
python和php哪个容易学
Jun 19 Python
python跨文件使用全局变量的实现
Nov 17 Python
详解Python3 pandas.merge用法
Sep 05 #Python
python爬虫 猫眼电影和电影天堂数据csv和mysql存储过程解析
Sep 05 #Python
python爬取Ajax动态加载网页过程解析
Sep 05 #Python
python实现静态服务器
Sep 05 #Python
python编写简单端口扫描器
Sep 04 #Python
python 3.6.7实现端口扫描器
Sep 04 #Python
python用线性回归预测股票价格的实现代码
Sep 04 #Python
You might like
PHP 实现判断用户是否手机访问
2015/01/21 PHP
php生成过去100年下拉列表的方法
2015/07/20 PHP
搭建Vim为自定义的PHP开发工具的一些技巧
2015/12/11 PHP
php使用strip_tags()去除html标签仍有空白的解决方法
2016/07/28 PHP
thinkPHP分页功能实例详解
2017/05/05 PHP
对php 判断http还是https,以及获得当前url的方法详解
2019/01/15 PHP
超级24小时弹窗代码 24小时退出弹窗代码 100%弹窗代码(IE only)
2010/06/11 Javascript
JSON格式化输出
2014/11/10 Javascript
JS验证逗号隔开可以是中文字母数字
2016/04/22 Javascript
jQuery 实现评论等级好评差评特效
2016/05/06 Javascript
详解angular中的作用域及继承
2017/05/31 Javascript
JavaScript严格模式下关于this的几种指向详解
2017/07/12 Javascript
vue实现todolist功能、todolist组件拆分及todolist的删除功能
2019/04/11 Javascript
JS实现普通轮播图特效
2020/01/01 Javascript
js实现点赞效果
2020/03/16 Javascript
vue相关配置文件详解及多环境配置详细步骤
2020/05/19 Javascript
python定时采集摄像头图像上传ftp服务器功能实现
2013/12/23 Python
python实现读取命令行参数的方法
2015/05/22 Python
Python使用sftp实现上传和下载功能(实例代码)
2017/03/14 Python
Python实现批量压缩图片
2018/01/25 Python
python 划分数据集为训练集和测试集的方法
2018/12/11 Python
Flask框架重定向,错误显示,Responses响应及Sessions会话操作示例
2019/08/01 Python
如何打包Python Web项目实现免安装一键启动的方法
2020/05/21 Python
HTML5+CSS设置浮动却没有动反而在中间且错行的问题
2020/05/26 HTML / CSS
大众服装店创业计划书范文
2014/01/01 职场文书
给小学生的新年寄语
2014/04/04 职场文书
英文推荐信格式范文
2014/05/09 职场文书
“三支一扶”支教教师思想汇报
2014/09/13 职场文书
家庭贫困证明范本(经典版)
2014/09/22 职场文书
2014大学班主任工作总结
2014/11/08 职场文书
2016年春节慰问信息大全
2015/11/30 职场文书
Python极值整数的边界探讨分析
2021/09/15 Python
springboot如何接收application/x-www-form-urlencoded类型的请求
2021/11/02 Java/Android
《艾尔登法环》1.03.3补丁上线 碎星伤害调整
2022/04/06 其他游戏
SpringBoot 集成短信和邮件 以阿里云短信服务为例
2022/04/22 Java/Android
Python实现数据的序列化操作详解
2022/07/07 Python