使用Selenium使用部分id循环遍历值
我想使用使用Selenium使用部分id循环遍历值,selenium,Selenium,我想使用xpath遍历许多不同的值,但出于某种原因,我的代码一遍又一遍地遍历相同的值。在下面的代码中使用Python m = 0; classPREFIX = []; while True: try: ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,); dep
xpath
遍历许多不同的值,但出于某种原因,我的代码一遍又一遍地遍历相同的值。在下面的代码中使用Python
m = 0;
classPREFIX = [];
while True:
try:
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,);
departmentClass = WebDriverWait(browser, 10,ignored_exceptions=ignored_exceptions).until(expected_conditions.presence_of_element_located((By.XPATH, "//*[contains(@id, 'partial-id-name')]")));
classPREFIX.append(departmentClass.text);
print(classPREFIX[m])
m += 1;
except Exception:
print("indexed outta bounds in classes prefix");
break;
在HTML中,有多个具有部分id名称的元素,但是它们后面有不同的数字。比如说
<div
<id = "randomText3_partial-id-name_1" >
</div>
<div
<id = "randomText5_partial-id-name_2" >
</div>
<div>
<id = "randomText0_partial-id-name_3" >
</div>
需要对脚本稍作修改
m = 0;
classPREFIX = [];
while (m<=len(browser.find_elements_by_xpath("//*[contains(@id, 'partial-id-name')]"))):
try:
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException);
departmentClass = WebDriverWait(browser, 10,ignored_exceptions=ignored_exceptions).until(expected_conditions.presence_of_element_located((By.XPATH, "//*[contains(@id, 'partial-id-name')]")));
classPREFIX.append(browser.find_elements_by_xpath(("//*[contains(@id, 'partial-id-name')]"))[m].text);
print(classPREFIX[m])
m += 1;
except Exception:
print("indexed outta bounds in classes prefix");
break;
m=0;
classPREFIX=[];
虽然(mThanks表示响应,但是代码不起作用。1)FindElements应该是find_elements()2)xpath应该大写3)find_elements中的语法应该是find_elements((By.xpath,“/*[contains(@id,'partial id name')])。我认为您提出的建议比Python更面向Java。然而,在做了这些更改之后,我得到了一个错误,即使用.size()时“TypeError:'str'对象不可调用”。此外,使用.get(m)不会向classPREFIX追加任何值。你知道为什么吗?尽管你没有在问题中指定语言标签,我还是会想出来的。请检查更新的答案。它成功了,谢谢!但是,您应该删除第7行中的By.xpath,因为这会导致错误,应该改为classPREFIX.append(browser.find_elements_By_xpath(“/*[contains(@id,'partial id name')]))[m].text);