以‘房天下’网站为例,因为它的登录还没有设置反爬虫模式。。偷笑
from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
url = 'https://www.fang.com/default.htm'
login_text = '登录'
login_account='/html/body/div[2]/div[2]/div[1]/dt/span[2]'
account = '******' #用自己注册的账号登录
pwd = '********'
def test():
browser = OpenBrowser() #调用浏览器
Openurl(browser,url) #打开具体网址
ele_dict = {'text_id':login_text,'login_account1':login_account,'userid':'username',\
'pwdid':'password','loginid':'loginWithPswd'}
account_dict= {'uname':account,'pwd':pwd}
ele_tuple = findElement(browser,ele_dict)
#因为浏览器自动关闭了,不知道为啥,所以这里添加了return url,然后再打开一次url
open(sendVals(browser,ele_tuple,account_dict))
#打开浏览器
def OpenBrowser():
usebrowser = webdriver.Chrome()
return usebrowser
#传入句柄和参数,打开Juin网址
def Openurl(handle,url):
handle.get(url)
handle.maximize_window()
def get_ele_times(driver,times,func):
return WebDriverWait(driver,times).until(func)
#查找元素
def findElement(d,arg):
'''
arg must be dict
1、text_id
2、user_id
3、pwd
4、login_id
:return userEle ,pwdEle,, loginEle
'''
if 'text_id' in arg: #判断是否有登录字段
#ele_login = get_ele_times(d,10,lambda d:d.find_element_by_link_text(arg['text_id']))
d.find_element_by_link_text(arg['text_id']).click()
print(d.current_window_handle) #打印当前网页句柄
# ele_login.click()
time.sleep(5)
if 'login_account1' in arg:
# ele_login1 = get_ele_times(d, 10, lambda d: d.find_element_by_link_text(arg['login_account1']))
#ele_login1.click()
#d.find_element_by_link_text(arg['login_account1']).click()
d.find_element_by_xpath(arg['login_account1']).click()
print('打印出来了:{}'.format(d.current_window_handle))
print('i do it ')
useEle = d.find_element_by_id(arg['userid'])
pwdEle = d.find_element_by_id(arg['pwdid'])
loginEle = d.find_element_by_id(arg['loginid'])
return useEle,pwdEle,loginEle
#
def sendVals(d,eletuple,arg): #browser传递进来
'''
ele tuple
account : uname,pwd
'''
listkey = ['uname','pwd']
# i=0
# for key in listkey:
# eletuple[i].send_keys('')
# eletuple[i].clear()
# eletuple[i].send_keys(arg[key])
# i+=1
#
for i,key in enumerate(listkey): #其实就遍历listkey = ['uname','pwd']
print(i,key)
eletuple[i].send_keys('')
eletuple[i].clear()
eletuple[i].send_keys(arg[key])
eletuple[2].click()
time.sleep(3)
return d.current_url
#主程序
if __name__ == '__main__':
test()