Python: clicking a button [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-07 16:48:41

问题


I have problems in clicking this button that looks in HTML code like this:

<form method="post">
<br>
<input type="hidden" value="6" name="deletetree">
<input type="submit" value="Delete Tree" name="pushed">
</form>

and the url that needs to be generated looks like this: http://mysite.com/management.php?Category=2&id_user=19&deteletree=6&pushed=Delete+Tree

Update: I tried this, but it doesnt work:

form_data = urllib.urlencode({'Category' : '2', 'suid' : '19', 'deletetree' : '6', 'pushed' : 'Delete+Tree' })
urllib2.urlopen("management.php", form_data)

This is how I log in:

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13')] 
username = "user" 
password = "pass" 
USER_ID = '6'

    loginonsite = login("http://mysite.com/myprofile.php",
                        "login_username=%s&login_password=%s&suid=%s".format(username, password, USER_ID)

)


回答1:


You could use requests to make a post.

import requests
data = {'Category' : '2', 'suid' : '19', 'deletetree' : '6', 'pushed' : 'Delete+Tree' }
response = requests.post('http://mysite.com/management.php', data=data)

print response.text

As more and more of the content of a webpage is generated in JavaScript I find myself using Selenium's webdriver to directly drive a real browser like Chrome when I'm doing this kind of automation now...

Update: Sounds like you need to login first

Now, requests can pass cookies through as well. So you to send a logged in request you would do this

login_data = data={'username': 'user', 'password': 'pass'
post_data = {
    'Category' : '2', 'suid' : '19', 'deletetree' : '6', 'pushed' : 'Delete+Tree'
}
login_response = requests.get('http://mysite.com/myprofile.php', data=login_data)
form_response = requests.post(
    'http://mysite.com/management.php',
     data=post_data, 
     cookies=login_response.cookies
)

So, you do the login, then use the cookies in the response in the next request. Should work. But obviously I can't test that code for your exact situation.



来源:https://stackoverflow.com/questions/15063091/python-clicking-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!