Python之爬虫urllib(一)

目录

本节介绍的信息内容 

包含模块

网页编码问题解决

urlopen 的返回对象(在例子中指的是rsp)


包含模块

  • urllib.request: 打开和读取urls
  • urllib.error: 包含urllib.request产生的常见的错误,使用try捕捉
  • urllib.parse:  包含解析url的方法
  • urllib.robotparse: 解析robots.txt文件
  •  案例1
from urllib import request
'''
使用urllib.request请求一个网页内容,并把内容打印出来
'''


if __name__ == '__main__':

    url = "http://jobs.zhaopin.com/195435110251173.htm?ssidkey=y&ss=409&ff=03&sg=2644e782b8b143419956320b22910c91&so=1"
    # 打开相应url并把相应页面作为返回
    rsp = request.urlopen(url)

    # 把返回结果读取出来
    # 读取出来内容类型为bytes
    html = rsp.read()
    print(type(html))

    # 如果想把bytes内容转换成字符串,需要解码
    html = html.decode("utf-8")

    print(html)

网页编码问题解决

  • chardet 可以自动检测页面文件的编码格式,但是,可能有误
  • 需要安装,安装方法:在python的安装文件夹的scripts文件夹里面有个pip.exe文件,安装时需要用到这个(貌似python2.4版本以上才默认有这个功能),在命令行模式下进入pip.exe所在的文件夹,然后在命令提示符中输入pip.exe install chardet
  • Python获取网页编码的两种方法——requests.get、chardet
  • 案例2
'''
利用request下载页面
自动检测页面编码

'''

import urllib
import chardet

if __name__ == '__main__':
    url = 'http://stock.eastmoney.com/news/1407,20170807763593890.html'

    rsp = urllib.request.urlopen(url)

    html = rsp.read()

    #1、利用 chardet自动检测
    cs = chardet.detect(html)
    print(type(cs))
    print(cs)


    #2、使用get取值保证不会出错
    html = html.decode(cs.get("encoding", "utf-8"))
    print(html)

 urlopen 的返回对象(在例子中指的是rsp)

  • 返回对象具有的函数
    • geturl: 返回请求对象的url
    • info: 请求反馈对象的meta信息
    • getcode:返回的http code    
    • 案例3(也可以在 print(type(rsp)) 一行打上断点,然后看编辑器下方Console中给出的信息,可以得到URL等信息)
import urllib

if __name__ == '__main__':
    url = 'http://stock.eastmoney.com/news/1407,20170807763593890.html'

    rsp = urllib.request.urlopen(url)

    print(type(rsp))
    print(rsp)

    print("URL: {0}".format( rsp.geturl()))
    print("Info: {0}".format(rsp.info()))
    print("Code: {0}".format(rsp.getcode()))

    html = rsp.read()

    # 使用get取值保证不会出错
    html = html.decode()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ydw_ydw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值