Python读取网页内容的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python读取网页内容的方法。分享给大家供大家参考。具体如下:

import urllib2
#encoding = utf-8
class Crawler:
  def main(self):
    #req = urllib2.Request('http://www.baidu.com/')
    #req.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:5.0)')
    #urllib2.socket.setdefaulttimeout(10) # 超时10秒
    #page = urllib2.urlopen(req)
    page = urllib2.urlopen('http://www.google.com', timeout=10)
    data = page.read()
    print data
    print len(data) #计算字节长度
if __name__ == '__main__':
  me=Crawler()
  me.main()

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python学习笔记之os模块使用总结

复制代码 代码如下: #!/usr/bin/env python ##-*- coding: utf-8 -*-   import os   print "n欢迎大家...

python使用matplotlib库生成随机漫步图

python使用matplotlib库生成随机漫步图

本教程使用python来生成随机漫步数据,再使用matplotlib将数据呈现出来 开发环境 操作系统: Windows10 IDE: Pycharm 2017.1.3 Python...

Python程序暂停的正常处理方法

将进程挂起(Suspend) 而非 阻塞(Block) 如果用sleep() 进程将阻塞 假设进程下有两个线程 那么这两个线程会继续运行 要使进程挂起 可以考虑使用psutil im...

python encode和decode的妙用

>>> "hello".encode("hex") '68656c6c6f' 相应的还可以 >>> '68656c6c6f'.decode("hex"...

Python2.x和3.x下maketrans与translate函数使用上的不同

maketrans和translate函数是进行字符串字符编码的常用方法。本文着重点在于演示其基本用法和在不同版本下操作的差异。本文提到的2.X版本指2.6以上的版本,3.X版本指3.1...