我不是一个非常有经验的编码员,如果我说傻话的话,我深表歉意。
我正在使用Python(在Spyder中)让Selenium填写包含用户名和密码的网站表单。目标是link。
当我在常规浏览器中按F12查找“用户名”元素时,会得到以下信息:
<input class="slds-input input" type="text" aria-describedby="" placeholder="Username" id="172:0" data-aura-rendered-by="176:0" data-interactive-lib-uid="2">
因此,我尝试使用ID来定位元素。但是,当我运行脚本时,在Chrome中出现以下错误:
NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"[id="172:0"]"}
与在Firefox中运行时相同:
NoSuchElementException: Unable to locate element: [id="172:0"]
当我在Selenium驱动的浏览器中检查HTML时,可以看到页面代码(即元素ID)不同,如下所示
<input class="slds-input input" type="text" aria-describedby="" placeholder="Username" id="78:2;a" data-aura-rendered-by="82:2;a" data-interactive-lib-uid="2">
我的最佳猜测是HTML代码中的差异是错误的原因。我发现人们发布了类似的问题,但是有些问题略有不同,我无法使用那里提出的解决方案来解决我的问题。我希望有人可以帮助解决我的问题。
答案 0 :(得分:0)
使用xpath代替id
,因为它会动态更改
用户名的Xpath://label/following-sibling::input
密码的Xpath://lightning-input//div//input
在python中使用上述xpath进行转换的示例工作代码在Java中工作,并在启动网站之前添加implicitlyWait
和pageLoadTimeout
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://lta-tennis.force.com/"); // WebElement
driver.findElement(By.xpath("//label/following-sibling::input")).sendKeys("dummy");
driver.findElement(By.xpath("//lightning-input//div//input")).sendKeys("dummy");
System.out.println(driver.getTitle());
答案 1 :(得分:0)
尝试这些xpath
//input[@placeholder="Username"]
//input[@placeholder="Password"]
这是完整的代码
from selenium import webdriver
import time
browser = webdriver.Chrome('C:\\driverpath\\chromedriver.exe')
url = 'https://lta-tennis.force.com/s/login/'
get = browser.get(url)
time.sleep(5)
browser.find_element_by_xpath('//input[@placeholder="Username"]').send_keys('hello')
browser.find_element_by_xpath('//input[@placeholder="Password"]').send_keys('pass')