【发布时间】:2020-03-30 16:24:55
【问题描述】:
如果我在特定页面上运行此循环并且代码无法在循环内确定的位置找到 xPath,我希望循环结束。这是循环:
for i in range(1, maxListingsForLoops): #@@@ADVERT NUMBER@@@
if i > 10:
break
xPath = "/html/body/main/div[2]/div/div[5]/div[" +str(i)+ "]/div[1]/a[2]"
getRenew = browser.find_elements_by_xpath(xPath)
getRenew = getRenew.get_attribute('href')
#browser.get(getRenew)
print(getRenew)
time.sleep(speed)
当我逐行运行循环时,我可以看到变量是 [],猜测这意味着它是空的,这是有道理的,因为在此页面上没有完整的列表页面,所以在五次循环之后它不会返回任何内容. 我目前收到此错误:
$ xPath = "/html/body/main/div[2]/div/div[5]/div[7]/div[1]/a[2]"
$ print(xPath)
>>>>/html/body/main/div[2]/div/div[5]/div[7]/div[1]/a[2]
$ getRenew = browser.find_elements_by_xpath(xPath)
$ print(getRenew)
>>>>[]
$ getRenew = getRenew.get_attribute('href')
>>>>Traceback (most recent call last):
>>>> File "<input>", line 1, in <module>
>>>>AttributeError: 'list' object has no attribute 'get_attribute'
有谁知道当 xPath 变量返回零、null 或空时如何结束循环?
谢谢。
【问题讨论】:
标签: python selenium loops xpath null