[英]How to type data from list to a website using python and selenium?
我是編碼方面的初學者,我想使用python和selenium將數據從列表輸入到特定網站,並跟蹤該數據。 當前使用的代碼是>
inputElement = driver.find_element_by_xpath('//*[@id="username"]')
inputElement.send_keys("example@email.com")
inputElement = driver.find_element_by_xpath('//*[@id="password"]')
inputElement.send_keys("passwordexample")
我試圖用列表中的數據替換“ example@email.com”“ passwordexample”,如果數據格式如下:
我不知道如何制作該列表以及如何從該列表中逐行獲取數據
我猜想您的意思是您想為電子郵件和密碼創建存儲(在本例中為字典)。
my_dict = {example@email.com: passwordexample,
example2@email.com: passwordexample2,
example3@email.com: passwordexample3}
同樣,不確定“列表”是什么意思(似乎不是在指代實際的python列表)。 同樣也不確定“獲取數據”的含義。
您還將要更改用戶名或密碼框的變量名。 所以也許更像這樣:
inputElement_user = driver.find_element_by_xpath('//*[@id="username"]')
inputElement_pass = driver.find_element_by_xpath('//*[@id="password"]')
# Loop through every user & pass and do what you wish
for k, v in my_dict.items():
inputElement_user.send_keys(k)
inputElement_pass.send_keys(v)
# Insert whatever else you want to do on the page
假設“ example@email.com:passwordexample”為字符串形式,您可以使用split()方法實現它,但不清楚
data = "example@email.com:passwordexample"
#seperate values using : seperator from the string
datalist = data.split(':')
inputElement = driver.find_element_by_xpath('//*[@id="username"]')
#use index on list to get required value datalist[0] will give you example@email.com
inputElement.send_keys("datalist[0]")
inputElement = driver.find_element_by_xpath('//*[@id="password"]')
#datalist[1] will give you passwordexample
inputElement.send_keys("datalist[1]")
我如何解決這個問題? -首先是使用username:password格式的文件。 我還制作了另外兩個單獨的文本文件,例如username.txt和password.txt
然后我使用正則表達式對一行中的單詞進行計數,然后使用計數值在需要的地方分割文本,因為我的文本可能像這樣:
等等。 由於密碼在單詞之間永遠不會有空格,因此最后一個單詞始終是密碼。
import regex
lineinfo = open("allaccounts.txt", "r")
username = open("username.txt", "w")
password = open("password.txt", "w")
info = lineinfo.readline()
info2 = info.replace(':', ' ')
count = len(regex.findall(r'\S+', info2))
if count == 2:
info3 = info2.split()[0]
username.write(info3)
info4 = info2.split()[1]
password.write(info4)
if count == 3:
info3 = info2.split()[0]
info5 = info2.split()[1]
username.write(info3 + " " + info5)
info4 = info2.split()[2]
password.write(info4)
username.close() and password.close()
username = open("username.txt", "r")
password = open("password.txt", "r")
real_username = username.readline()
real_password = password.readline()
username.close()
password.close()
是的,也許可以用一種更簡單的方法來完成,但是我四天前開始講授代碼,這就是我可以立即提出的想法。
所以用戶名將是rea_username和密碼real_password,我像這樣使用它們
inputElement = driver.find_element_by_xpath('//*[@id="username"]')
inputElement.send_keys("real_username")
inputElement = driver.find_element_by_xpath('//*[@id="password"]')
inputElement.send_keys("real_password")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.