如何使用python登录网站?

时间:2010-12-11 01:28:18

标签: python authentication

我已经看到了另一个问题:How to use Python to login to a webpage and retrieve cookies for later usage?

然而,直接修改该答案并不适合我,所以我想知道如何实现我的目标。

要提供上下文,我尝试登录https://mog.com/hp/sign_in,然后从以下页面中提取播放列表的名称:http://mog.com/my_mog/playlists

我认为对于知道自己在做什么的人来说,这应该是非常简单的。登录网站并访问受密码保护的页面的一些基本代码会很棒,如果你能用一两句话解释一下代码中的每一行是什么,那就更好了,这样我就能更好地理解代码正在做什么。

1 个答案:

答案 0 :(得分:12)

尝试mechanize

import mechanize
br=mechanize.Browser()
br.open('https://mog.com/hp/sign_in')
br.select_form(nr=0) 
br['user[login]']= your_login
br['user[password]']= your_password
br.submit()
br.retrieve('http://mog.com/my_mog/playlists','playlist.html')

修改
要获取您的链接,您可以添加:

for link in br.links():
    print link.url, link.text

或者,从playlist.html开始,您可以使用Beautifulsoup和正则表达式:

from BeautifulSoup import BeautifulSoup
import re
soup = BeautifulSoup(file('playlist.html').read())
for link in soup.findAll('a', attrs={'href': re.compile("your matching re")}):
    print link.get('href')