python学习(三)--跟着例子写的贴

发布时间:2019-05-22 22:11:50编辑:auto阅读(1903)

    from urllib import request
    import urllib

    #爬贴吧网页文件到本地。首先在本地打开百度贴吧 搜索 java吧
    #第一页的内容是:http://tieba.baidu.com/f?ie=utf-8&kw=java&fr=search&red_tag=f0746297280
    #第二页 http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=50
    #第三页 http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=100
    #第四页 http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=150
    #看规律 只有第一页比较特殊 把第一页换成:http://tieba.baidu.com/f?kw=java&ie=utf-8&pn=0 也是可以的
    #也就是地址栏实际上是 http://tieba.baidu.com/f?kw=java(如果是中文需要转码)&ie=utf-8&pn=0(格式为:(页数-1)*50)

    def load_file(url, fname):
    print("正在下载:"+fname)
    # 水果手机的safari
    header = {"user-agent":
    "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5"}
    req = request.Request(url, headers=header)
      #这里是read方法 就读取到了原始网页  开始加了decode方法,结果报类型错误。decode方法把内容解析成了一个字符串

    data = request.urlopen(req).read()
        return data






    def spider(url, begin, end, fileName):
    #rang函数 理解的类似于java的字符串切割的包左不包右原则,所以需要+1
    for page in range(begin, end+1):
    url = url +str((page-1)*50)
    fname = fileName +str(page) +"页.html"
    html = load_file(url, fname)
    writePage(html, fname)


    def writePage(html, fname):
    print("正在保存:"+fname)
    #存放位置
    targetLoaction = "D:\浏览器下载目录\images" + "\\"+fname
    print("保存文件为:"+targetLoaction)
    with open(targetLoaction, "wb") as f:
    f.write(html)

    print(fname+"爬取成功")


    if __name__ == "__main__":
    name = input("请输入要爬取的贴吧名:")
    begin = int(input("请输入起始页:"))
    end = int(input("请输入尾页:"))

    if int(begin) > int(end) :
    print("起始页不可大于尾页")
    quit()

    #组装url
    kw = urllib.parse.urlencode({"kw":name})
    url = "http://tieba.baidu.com/f?kw="+kw+"&ie=utf-8&pn="
    fileName = "爬取"+name+"吧第"

    spider(url, begin, end, fileName);




关键字