• python mechanize自动登录程序


    放假回来了,很久没更新博客了,以后得常更新,今天给大家分享下python第3方的模块包:mechanize
    mechanize是非常合适的模拟浏览器的模块,它的特点主要有:

    1 http,https协议等。
    2 简单的HTML表单填写。
    3 浏览器历史记录和重载。
    4 Referer的HTTP头的正确添加(可选)。
    5 自动遵守robots.txt的。
    6 自动处理HTTP-EQUIV和刷新。

    所以你可以用mechanize来完成一些自动化浏览器想要做的事情,比如自动登录表单,自动填写表单等。
    首先你在mechanize download页面里面下载并且安装好
    然后可以看下文档:http://wwwsearch.sourceforge.net/mechanize/

    下面是我写的简单代码:

    #导入模块##
    import mechanize
    import cookielib
    from BeautifulSoup import BeautifulSoup


    br = mechanize.Browser()
    cj = cookielib.LWPCookieJar()
    br.set_cookiejar(cj)##关联cookies

    ###设置一些参数,因为是模拟客户端请求,所以要支持客户端的一些常用功能,比如gzip,referer等
    br.set_handle_equiv(True)
    br.set_handle_gzip(True)
    br.set_handle_redirect(True)
    br.set_handle_referer(True)
    br.set_handle_robots(False)

    br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

    ###这个是degbug##你可以看到他中间的执行过程,对你调试代码有帮助
    br.set_debug_http(True)
    #br.set_debug_redirects(True)
    #br.set_debug_responses(True)

    br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.11) Gecko/20100701 Firefox/3.5.11')]##模拟浏览器头
    response = br.open('http://xxx..com/')##自己设定一个url

    for f in br.forms():##有的页面有很多表单,你可以通过来查看
    print f

    br.select_form(nr=1)##选择表单1,

    br.form['username'] = '用户账户'
    br.form['password'] = '密码'

    br.submit()##提交表单

    print 'success login'

  • 相关阅读:
    无符号数和有符号数之间赋值和大小比较
    (转)关于Linux核心转储文件 core dump
    mysql忘记root密码解决办法
    CentOS7安装iptables防火墙
    CENTOS7下安装REDIS
    iptables命令(备忘)
    ps 命令详解
    virtualenv
    How to Baskup and Restore a MySQL database
    linux 用户/用户组添加修改删除(ubuntu/centos)
  • 原文地址:https://www.cnblogs.com/wanpython/p/2794563.html
Copyright © 2020-2023  润新知