本文将介绍python里常用的模块。如未特殊说明,所有示例均以python3.4为例:

$ python -VPython 3.4.3

网络请求

urllib

urllib提供了一系列用于操作URL的功能。通过urllib我们可以很方便的抓取网页内容。

抓取网页内容

# coding: utf-8import urllib.request

url = 'https://api.douban.com/v2/book/2129650'with urllib.request.urlopen(url) as f:
    headers = f.getheaders() # 报文头部
    body = f.read() # 报文内容

    print(f.status, f.reason) # 打印状态码、原因语句
    for k,v in headers:
        print(k + ': ' + v)

    print(body.decode('utf-8'))

抓取百度搜索图片

import urllib.requestimport osimport reimport time
url=r'http://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1488722322213_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%A3%81%E7%BA%B8%E5%B0%8F%E6%B8%85%E6%96%B0&f=3&oq=bizhi%E5%B0%8F%E6%B8%85%E6%96%B0&rsp=0'imgPath=r'E:\img'if not os.path.isdir(imgPath):
    os.mkdir(imgPath)

imgHtml=urllib.request.urlopen(url).read().decode('utf-8')#test html#print(imgHtml)urls=re
        
		

网友评论