• python爬虫-基础入门-爬取整个网站《2》


    python爬虫-基础入门-爬取整个网站《2》

    描述:

      开场白已在《python爬虫-基础入门-爬取整个网站《1》》中描述过了,这里不在描述,只附上 python3 的代码。

    python3 脚本代码:

     1 #-*- coding: utf-8 -*-
     2 
     3 import urllib.request
     4 
     5 
     6 def baiduNet() :
     7 
     8     response = urllib.request.urlopen("http://www.baidu.com")
     9     netcontext = response.read().decode("utf-8")
    10 
    11     file = open("baidutext.txt", "w", encoding='UTF-8')
    12     file.write(netcontext)
    13 
    14 if __name__ == "__main__" :
    15     baiduNet()

    注意:

      在python3中包urllib2归入了urllib中,所以要导入urllib.request,并且要把urllib2替换成urllib.request

    urlopen方法

    >> 获取页面信息

    >> 语法形式

      urllib.request.urlopen(url, data=None, [timeout])

      -> url : 需要打开的网址

      -> data : post需要提交的数据

      -> timeout : 设置网站的访问超市时间

    >> 结果:

      response = urllib.request.urlopen("http://www.baidu.com")

      netcontext = response.read().decode("utf-8")

      使用read()方法读取响应对象中的文本,注意:得到文本数据格式为byte类型,需要decode()方法解码,转换成string类型。

      

    --->>> 扩展,urlopen其它方法

    方法 功能
    read(),readline(),readlines(),fileno(),close() 对HHTTPResponse类型数据进行操作
    info() 返回HTTPMessage对象,表示远程服务器返回的头信息
    getcode() 返回Http状态码,如果是http请求,200请求成功状态码;404网址未找到
    geturl() 返回请求的url

     

     

     

     

     

     

     

     

    如有问题,欢迎纠正!!!

    如有转载,请标明源处:https://www.cnblogs.com/Charles-Yuan/p/9903242.html

     

  • 相关阅读:
    yum 在线安装LAMP
    python-scrapy-增量式
    python-scrapy-分布式爬取
    python-scrapy-全站数据爬取-CrawlSpider
    python-scrapy-中间件的学习
    python-scrapy深度爬取
    python-scrapy环境配置
    django DOM
    window10设置环境变量(以设置虚拟环境和SQL为例)
    加入园子啦
  • 原文地址:https://www.cnblogs.com/Charles-Yuan/p/9903242.html
Copyright © 2020-2023  润新知