【问题标题】:How to end a loop if null returned?如果返回null,如何结束循环?
【发布时间】: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


    【解决方案1】:

    尝试以下方法:

    if not browser.find_elements_by_xpath(xPath):
        break
    

    【讨论】:

    • 真的很抱歉,不明白这段代码应该加在哪里?我在此行之前和之后尝试过:getRenew = browser.find_elements_by_xpath(xPath) 但都导致错误。
    • 这取决于你想退出循环的时间——如果你想这样做,如果browser.find_elements_by_xpath(xPath)返回空/空列表,然后添加if。
    • @C00P3RR 我已经编辑了我的答案。这对你有意义吗?
    • 是的,它确实有帮助!但我得到了错误:指向 xPath 变量周围右括号的无效语法。
    • 我认为这无关。这可能与您的 xPath 变量有关。尝试将其更改为:xPath = f"/html/body/main/div[2]/div/div[5]/div[{i}]/div[1]/a[2]"
    猜你喜欢
    • 2017-09-30
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2011-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多