Python implements douban. fm simple client

Source: Internet
Author: User
A month ago, I tried to use python to implement a simple douban. fm client. I plan to gradually improve it into a replacement for the douban. fm client of the web version in Ubuntu. But since... A month ago, I tried to use python to implement a simple douban. the fm client is planned to gradually improve it into a douban that can replace the web version in Ubuntu. fm client. However, since there were so many things, they were put aside and were not improved. Just yesterday, a garden friend mentioned the login implementation in his comment. although there are still many issues recently, he suddenly wanted to implement this function. Just a few days ago, due to some needs, I used python to implement website login. I guess this douban. fm login will not be too bad.


About website authentication

Http is designed as a connectionless protocol, but in reality, many websites need to identify users, and cookies are born for this. When we use a browser to browse a website, the browser will handle cookies transparently. However, if we want to log on to a third-party website, we must have a certain understanding of the cookie workflow.


In addition, many websites use the verification code mechanism to prevent automatic login. the intervention of the verification code will make the login process troublesome, but it is not too difficult to handle.


In reality, the login process of douban. fm

To simulate a clean login process (without using an existing cookie), I use the chromium stealth mode.

It is worth noting that python provides three http libraries: httplib, urllib, and urllib2. urllib2 is the one that can transparently process cookies. it is painful to use httplib to manually process cookies.

The code is as follows:

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(CookieJar()))captcha_id = opener.open(urllib2.Request('http://douban.fm/j/new_captcha')).read().strip('"')captcha = opener.open(urllib2.Request('http://douban.fm/misc/captcha?size=m&id=' + captcha_id)).read())file = open('captcha.jpg', 'wb')file = write(captcha)file.close()

This code downloads the verification code.

Then, fill in the form and submit it.

The destination address of the logon form is http://douban.fm/j/login:

Source: radio

Alias: User name

Form_password: password

Captcha_solution: verification code

Captcha_id: verification code ID

Task: sync_channel_list

The next step is to construct a form using python.

opener.open(    urllib2.Request('http://douban.fm/j/login'),    urllib.urlencode({        'source': 'radio',        'alias': username,        'form_password': password,        'captcha_solution': captcha,        'captcha_id': captcha_id,        'task': 'sync_channel_list'}))

The data returned by the server is in json format. the specific format is not mentioned here. you can test it by yourself.


How do we know if logon works? Yes. as mentioned in the previous article, channel =-3 is a red-hearted megahertz, which is a user's favorite list. if you are not logged on, you cannot obtain the playback list of this channel. Request http://douban.fm/j/mine/playlist? Type = n & channel =-3. if you return the music list you have added to your favorites, the logon takes effect.


Code sorting

Combining previous versions and new login functions, coupled with command line parameter processing and channel selection, a slightly improved douban. fm is complete.

View Code #! /Usr/bin/python # coding: UTF-8 import sys import OS import subprocess import getopt import time import json import urllib import urllib2 import getpass import ConfigParser from cookielib import CookieJar # save to file def save (filename, content ): file = open (filename, 'WB ') file. write (content) file. close () # obtain the playlist def getPlayList (channel = '0', opener = None): url =' http://douban.fm/j/mine/playlist?type=n&channel= '+ Channel if opener = None: return json. loads (urllib. urlopen (url ). read () else: return json. loads (opener. open (urllib2.Request (url )). read () # send the desktop notification def policysend (picture, title, content): subprocess. call (['Your Y-send', '-I', OS. getcwd () + '/' + picture, title, content]) # log on to douban. fm def login (username, password): opener = urllib2.build _ opener (urllib2.HTTPCookieProcessor (CookieJar () while True: print 'The verification code is being obtained ...... 'Captcha_id = opener. open (urllib2.Request (' http://douban.fm/j/new_captcha '). Read (). strip (' "') save ('verification code .jpg', opener. open (urllib2.Request (' http://douban.fm/misc/captcha?size=m&id= '+ Captcha_id). read () captcha = raw_input ('verification code:') print 'login ...... 'Response = json. loads (opener. open (urllib2.Request (' http://douban.fm/j/login '), Urllib. urlencode ({'source': 'Radio ', 'Alias': username, 'form _ password': password, 'captcha _ solution': captcha, 'captcha _ id ': captcha_id, 'task': 'sync _ channel_list '})). read () if 'err _ msg 'in response. keys (): print response ['err _ msg '] else: print 'login successful 'return opener # play douban. fm def play (channel = '0', opener = None): while True: if opener = None: playlist = getPlayList (channel) else: playlist = getPlayList (channel, opener) if playlist ['png'] = []: print 'an error occurred while obtaining the playlist. 'break picture, for song in playlist ['png']: picture = 'picture/'+ song ['picture']. split ('/') [-1] # download album cover save (picture, urllib. urlopen (song ['picture ']). read () # send a desktop notification yysend (picture, song ['title'], song ['artlist'] + '\ n' + song ['albumtitle']) # playing player = subprocess. popen (['mplayer', song ['URL']) time. sleep (song ['length']) player. kill () def main (argv): # default parameter channel = '0' user = ''password = ''# obtain and parse the command line parameter try: opts, args = getopt. getopt (argv, 'U: p: c: ', ['user =', 'password = ', 'Channel =']) doesn't getopt. getoptError as error: print str (error) sys. exit (1) # command line parameter processing for opt, arg in opts: if opt in ('-U',' -- user = '): user = arg elif opt in ('-p',' -- password = '): password = arg elif opt in ('-C', '-- channel = '): channel = arg if user = '': play (channel) else: if password ='': password = getpass. getpass ('password: ') opener = login (user, password) play (channel, opener) if _ name _ =' _ main __': main (sys. argv [1:])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.