分享一个常用的Python模拟登陆类

yipeiwu_com6年前Python基础

代码非常简单,而且注释也很详细,这里就不多废话了

tools.py

# -*- coding:utf8 -*-
'''
# =============================================================================
#   FileName: tools.py
#     Desc: 模拟浏览器
#    Author: cosven
#     Email: yinshaowen241@gmail.com
#   HomePage: www.cosven.com
#    Version: 0.0.1
#  LastChange: 2015-03-27 00:59:24
#    History:
# =============================================================================
'''
 
 
import urllib
import urllib2
import cookielib
 
 
class MyWeb():
  """
    模拟一个浏览器
  """
  def __init__(self):
    self.header = {
      'Host': 'music.163.com',
      'Content-Type': "application/x-www-form-urlencoded; charset=UTF-8",
      'Referer': 'http://music.163.com/song?id=26599525',
      "User-Agent": "Opera/8.0 (Macintosh; PPC Mac OS X; U; en)"
    }
    self.cookie = cookielib.LWPCookieJar()
    self.cookie_support = urllib2.HTTPCookieProcessor(self.cookie)
    self.opener = urllib2.build_opener(self.cookie_support,
                      urllib2.HTTPHandler)
    urllib2.install_opener(self.opener)
 
  def post(self, posturl, dictdata):
    """
    模拟post请求
 
    :param string posturl: url地址
    :param dict dictdata: 发送的数据
    """
 
    postdata = urllib.urlencode(dictdata)
    request = urllib2.Request(posturl, postdata, self.header)
    try:
      content = urllib2.urlopen(request)
      return content
    except Exception, e:
      print ("post:" + str(e))
      return None
 
  def get(self, url):
    """
    模拟get请求
 
    :param url: url地址
    :return content: 常使用read的方法来读取返回数据
    :rtype : instance or None
    """
    request = urllib2.Request(url, None, self.header)
    try:
      content = urllib2.urlopen(request)
      return content
    except Exception, e:
      print ("open:" + str(e))
      return None
 
 
if __name__ == "__main__":
  import hashlib
  web = MyWeb()
  url = 'http://music.163.com/api/login/'
  data = {
    'username': 'username', # email
    'password': hashlib.md5('password').hexdigest(), # password
    'rememberLogin': 'true'
  }
  res = web.post(url, data)
  print res.read()
  # url_add = 'http://music.163.com/api/playlist/manipulate/tracks'
  # data_add = {
  #   'tracks': '26599525', # music id
  #   'pid': '16199365',  # playlist id
  #   'trackIds': '["26599525"]', # music id str
  #   'op': 'add'  # opation
  # }
  # res_add = web.post(url_add, data_add)
  # print res_add.read()
 
  # 完了可以试着查看自己网易云音乐相应列表歌曲

以上就是本文给大家分享的代码了,希望大家能够喜欢,也希望能够对大家学习Python有所帮助。

相关文章

TensorFlow tf.nn.conv2d实现卷积的方式

实验环境:tensorflow版本1.2.0,python2.7 介绍 惯例先展示函数: tf.nn.conv2d(input, filter, strides, padding, us...

Python去除、替换字符串空格的处理方法

个人想到的解决方法有两种,一种是  .replace(' old ',' new ')   第一个参数是需要换掉的内容比如空格,第二个是替换成的内容,可以把...

python实现按任意键继续执行程序

在windows下写bat的时候,通过pause命令,可以暂停程序运行,例如经常见的程序会在终端提示”按任意键继续……”,用户在终端回车后程序可以接着运行,这个功能有多大用途今天暂且不说...

Python pickle模块实现对象序列化

这篇文章主要介绍了Python pickle模块实现对象序列化,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 作用 对Python对...

selenium获取当前页面的url、源码、title的方法

selenium获取当前页面的url、源码、title的方法

此篇博客学习的api如标题,分别是: current_url    获取当前页面的url; page_source    获取当前页面的源码; title        获取当前页面的t...