栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Python和Mechanize提交表单数据并进行身份验证

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Python和Mechanize提交表单数据并进行身份验证

我绝对建议尝试使用该API,但这对我有用(不适用于您的示例帖子,该示例帖子已删除,但适用于所有活动的帖子):

#!/usr/bin/env pythonimport mechanizeimport cookielibimport urllibimport loggingimport sysdef main():    br = mechanize.Browser()    cj = cookielib.LWPcookieJar()    br.set_cookiejar(cj)    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)    r= br.open('http://www.reddit.com')    # Select the second (index one) form    br.select_form(nr=1)    # User credentials    br.form['user'] = 'user'    br.form['passwd'] = 'passwd'    # Login    br.submit()    # Open up comment page    posting = 'http://www.reddit.com/r/PoopSandwiches/comments/f47f8/testing/'    rval = 'PoopSandwiches'    # you can get the rval in other ways, but this will work for testing    r = br.open(posting)    # You need the 'uh' value from the first form    br.select_form(nr=0)    uh = br.form['uh']    br.select_form(nr=7)    thing_id = br.form['thing_id']    id = '#' + br.form.attrs['id']    # The id that gets posted is the form id with a '#' prepended.    data = {'uh':uh, 'thing_id':thing_id, 'id':id, 'renderstyle':'html', 'r':rval, 'text':"Your text here!"}    new_data_dict = dict((k, urllib.quote(v).replace('%20', '+')) for k, v in data.iteritems())    # not sure if the replace needs to happen, I did it anyway    new_data = 'thing_id=%(thing_id)s&text=%(text)s&id=%(id)s&r=%(r)s&uh=%(uh)s&renderstyle=%(renderstyle)s' %(new_data_dict)    # not sure which of these headers are really needed, but it works with all    # of them, so why not just include them.    req = mechanize.Request('http://www.reddit.com/api/comment', new_data)    req.add_header('Referer', posting)    req.add_header('Accept', ' application/json, text/javascript, */*')    req.add_header('Content-Type', 'application/x-www-form-urlenpred; charset=UTF-8')    req.add_header('X-Requested-With', 'XMLHttpRequest')    cj.add_cookie_header(req)    res = mechanize.urlopen(req)main()

关闭javascript并查看reddit注释随后如何处理将是很有趣的。现在

magic
,在发布您的帖子时调用的onsubmit函数中会发生很多此类情况。这是
uh
and
id
值被添加的地方。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/633714.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号