如何用Python实现网页按钮的自动点击

Python023

如何用Python实现网页按钮的自动点击,第1张

用python的sendkeys直接模拟键盘,用ctype扩展来点鼠标。你需要做的就是用python打开浏览器,然后输入网站,在找到按钮的坐标(固定到程序里),然后点击就行了。不过简单的可以,复杂点的就要考虑很多问题了。

以登陆百度为例子,如下:

import urllib,urllib2,httplib,cookielib

def auto_login_hi(url,name,pwd):

url_hi="http://passport.baidu.com/?login"

#设置cookie

cookie=cookielib.CookieJar()

cj=urllib2.HTTPCookieProcessor(cookie)

#设置登录参数

postdata=urllib.urlencode({'username':name,'password':pwd})

#生成请求

request=urllib2.Request(url_hi,postdata)

#登录百度

opener=urllib2.build_opener(request,cj)

f=opener.open(request)

print f

#打开百度HI空间页面

hi_html=opener.open(url)

return hi_html

if __name__=='__main__':

name='name'

password='password'

url='yoururl'#例如:url='http://hi.baidu.com/cdkey51'

h=auto_login_hi(url,name,password)

print h.read()#h里面的内容便是登录后的页面内容

用selenium就可以了,它模拟打开浏览器,打开网页。

通过页面元素的特征,定位到要点击的元素,click()方法就可以完成点击

比如

self.driver.find_element_by_xpath('//ul[@class="uhomeTagList-ul"]/li[2]').click()