表单 form : <form action="#" enctype="application/x-www-form-urlencoded" method="post">
action 用于设置表单数据的提交地址;enctype 设置数据提交的编码;
输入:<input class="xxx" id="xxx" name="xxx" type="xxx" value=""/>
登录页面表单进入如下:
import urllib2,urllib
LOGIN_URL = "http://example.webscraping.com/user/login" # 登录页面网址
LOGIN_EMAIL = "example@webscraping.com" # 登录邮箱
LOGIN_PASSWORD = "example" # 登录密码
data = {"email":LOGIN_EMAIL,"password":LOGIN_PASSWORD}
# 进行 urlencode 编码
encoded_data = urllib.urlencode(data)
request = urllib2.Request(LOGIN_URL,encoded_data)
response = urllib2.urlopen(request)
print response.geturl() # 获取进入页面 url
"http://example.webscraping.com/user/login"
发现还是原来的登录网页,表明并没有登入进去。这是因为除了邮箱和密码外,还需要另外几个域。由于设置为 hidden,所以没有显示出来。为了访问这些隐藏域,使用 lxml 编写一个函数
import lxml.html
def parse_form(html):
tree = lxml.html.fromstring(html)
data = {}
for e in tree.cssselect("form input"):
if e.get("name"):
data[e.get("name")] = e.get("value")
return data
以上就把所有的 input 属性包括进 data 了,只要修改 data中的 email 和 password 值即可。(本来是"")
html = urllib2.urlopen(LOGIN_URL).read()
data = parse_form(html) # 上面定义的函数
# 修改 email 和 password 属性
data["email"] = LOGIN_EMAIL
data["password"] = LOGIN_PASSWORD
encoded_data = urllib.urlencode(data)
request = urllib2.Request(LOGIN_URL,encoded_data)
response = urllib2.urlopen(request)
print response.geturl()
"http://example.webscraping.com/user/login"
但是还是原来的登录界面,意味着登录又失败了,这是因为缺失了一个重要的组成部分--cookie 。当普通用户加载登录表单时,_formkey 的值将会保存在 cookie 中,然后该值会与提交的登录表单数据中的 _formkey 值进行对比。使用 urllib2.HTTPCookieProcessor 类增加 cookie 支持。
import cookielib
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
html = opener.open(LOGIN_URL).read()
# 后面就跟上面一样了
data = parse_form(html)
data["email"] = LOGIN_EMAIL
data["password"] = LOGIN_PASSWORD
encoded_data = urllib.urlencode(data)
request = urllib2.Request(LOGIN_URL,encoded_data)
response = opener.open(request) # 这里也有点不同
print response.geturl()
"http://example.webscraping.com"
登录成功。。。
使用 mechanize 模块实现自动化表单处理
安装: pip install mechanize
使用 mechanize 实现登录和编辑人口操作如下
import mechanize
br = mechanize.Browser() # 首先定义一个 machanize 浏览器对象
br.open(LOGIN_URL) # 定位到登录 URL
br.select_form(nr=0) # 选择登录表单
br["email"] = LOGIN_EMAIL # 直接传递邮箱密码
br["password"] = LOGIN_PASSWORD # 在提交之前,也可以调用 br.form 获取提交之前的表单状态
response = br.submit() # 提交选定的表单,然后就处于登录状态了
# 登录后编辑
br.open(COUNTRY_URL)
br.select_form(nr=0)
br["population"] = str(int(br["population"]) + 1)
br.submit()
这段代码比之前的例子要简单得多,因为我们不再需要管理 cookie ,而且访问表单输入框也更加容易。
本文介绍了如何使用Python实现网站的自动化登录过程,并通过表单处理进行数据提交。利用urllib2、cookielib和mechanize等库,详细演示了处理隐藏字段、管理cookie以及简化表单操作的方法。
55万+

被折叠的 条评论
为什么被折叠?



