我希望用户输入她/他的名字,然后将用户输入传递给selenium,以便它在我的网站的搜索字段中自动输入。可以先输入,然后按Enter,然后触发硒,将输入转发到浏览器。为什么不起作用?
from selenium import webdriver
import time
browser = webdriver.Chrome('C:/Users/acer/Desktop/chromedriver')
browser.get('website')
x = str(input('Your name: ')) #user inputs name here
if len(x) > 20: #the name van not be longer than 20 charachters
Print(’shorter’)
x # if longer than 20 input again
else: #if above is correct do following:
def user():
while True:
time.sleep(1)
try:
browser.find_element_by_id('q').send_keys(x) #find input field with html id q and input the name
browser.find_element_by_tag_name('button').click() #click next
user()
为了演示在用户名不超过20个字符时将用户输入传递给输入字段,下面是一个小程序,该程序执行以下操作:
name
name
是否小于5个字符。
break
则循环播放并将其传递name
到Google主页搜索框。continue
再次要求用户输入。代码块:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverException
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
browser = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
browser.get('https://www.google.com/')
while True:
name = str(input("Name please (max 5 charachters):"))
if len(name) > 5:
print("More than 5 charachters, please try again...")
continue
else:
break
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys(name)
控制台输出:
Name please (max 5 charachters):asdfgh
More than 5 charachters, please try again...
Name please (max 5 charachters):asdfghjkl
More than 5 charachters, please try again...
Name please (max 5 charachters):dev
对于20个字符长的用户输入,您可以遵循类似的逻辑,您的有效代码块将为:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
browser = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
browser.get('https://www.google.com/')
while True:
name = str(input("Name please (max 20 charachters):"))
if len(name) > 20:
print("More than 20 charachters, please try again...")
continue
else:
break
browser.find_element_by_id('q').send_keys(name) #find input field with html id q and input the name
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句