爬虫实践1

1.urllib

1.urllib.urlopen打开一个http链接,返回一个文件描述符
import urllib

def gethtml(url):
    s = urllib.urlopen(url)
    return s.read()

if __name__ == '__main__':
    print gethtml("http://www.baidu.com")

urllib.urlopen打开后返回的文件描述符有以下几种读取方式:

  • s.read(100) #读多少个字节
  • s.read() #读出所有字节
  • s.readline() #多出来一行
  • s.readlines() #读出所有行,放入一个列表
  • s.getcode() #返回状态码
  • s.close()把这个文件给关闭掉

不同的字符所占的字节是不同的, 不同编码中字符占用自己数不同(中文在utf-8中占用3个字节,gb2312占用2个字节)

2. HTTPMassage对象
import urllib

def gethtml(url):
    s = urllib.urlopen(url)
    return s.info()

if __name__ == '__main__':
    msg = gethtml("http://python.usyiyi.cn/documents/django_182/index.html")
    print msg

msg = s.info() //获取一个HTTPMassage的对象

  • msg.getheader(Content-Type) #getheader直接获取这个头
  1. 下载某个页面
import urllib

if __name__ == '__main__':
    filename, message = urllib.urlretrieve('http://python.usyiyi.cn/documents/django_182/index.html', 'index.html')
    print filename,'\n--------------\n', message

你可能感兴趣的:(爬虫实践1)