• urllib基础-请求对象request


    简单的案例-爬取百度首页

     1 from urllib import request
     2 '''
     3 爬取百度首页
     4 '''
     5 # 确定爬去目标
     6 base_url = 'http://www.baidu.com'
     7 
     8 # 发起http请求 返回一个类文件对象
     9 response = request.urlopen(url=base_url)
    10 
    11 # 获取相应内容
    12 html = response.read()
    13 
    14 # 把bytes类型转换成utf-8编码的字符串类型
    15 html = html.decode('utf-8')
    16 
    17 # 写入文件
    18 with open('baidu.html','w',encoding='utf-8') as f:
    19     f.write(html)

     

    response = request.urlopen(url=base_url)
      传入要爬取的网页的url,返回一个类文件对象,它可以像文件对象一样被操作。
      请求地址url,一般使用http,不使用https。https有的时候返回内容读取后不是网页的html内容。
    html = response.read()
      response是一个类文件对象,通过read()读取,返回内容的编码格式是bytes类型。
      python一般操作的都是字符串,将读取内容使用decode()进行编码。

    html = resoonse.read().decode('utf-8')
      decode('utf-8')设置编码格式为utf-8。这个编码是根据原网页的编码格式决定的。
      decode()默认的编码格式为utf-8。
      如果原网页的编码格式为gb2312,使用gbk编码格式也可以,引文gbk包含gbk2312。

    with open('baidu.html',mode='w',encoding='utf-8') as f:
      保存文件时,要指定编码格式。有时因为平台的不同,默认保存文件的编码格式不同。

  • 相关阅读:
    黑苹果安装 this is an unknown cpu model 0x3a
    JQMobile引入外部CSS,JS文件
    iphone系统更新 3002错误
    移动端HTML5框架
    花生壳动态域名解析使用
    win7 配置IIS + php 环境
    php在字符串中替换多个字符
    PHP 获取文件名和扩展名的方法
    Mysql无法创建外键的原因
    wordpress无法登录的解决方法
  • 原文地址:https://www.cnblogs.com/doitjust/p/9220522.html
Copyright © 2020-2023  润新知