【问题标题】:Selenium unable to get element cause by else-statementSelenium 无法通过 else 语句获取元素原因
【发布时间】:2021-04-25 21:57:42
【问题描述】:

这个问题的追求:Instagram have 2 type of xpath? How it could be remedied?我没有解决我的else-statement什么时候得到一个“私人档案”

它返回一个错误:

我的代码:

for follower in followers:
        #Iterate into the list
        browser.get(follower)
        sleep(2)
        
        if browser.find_element_by_css_selector("li:nth-of-type(2) a.-nal3 span").get_attribute("title"):
                print("Public profil")
                pass
              
        else:
            print("private profil")   
            pass

感谢您的支持

【问题讨论】:

    标签: python selenium if-statement instagram


    【解决方案1】:

    您需要在循环中将 if..else 子句替换为 try/except 块和 NoSuchElementException。这样,如果在每个循环中都没有找到该元素,它不应该崩溃

    for follower in followers:
            #Iterate into the list
            browser.get(follower)
            sleep(2)
        try:
            browser.find_element_by_css_selector("li:nth-of-type(2) a.-nal3 span").get_attribute("title"):
            print("Public profil")                   
        except NoSuchElementException:
            print("private profil")
    

    如果您想在到达私有配置文件后停止循环,只需在第二条 print() 语句后添加 break 即可

    要在脚本顶部添加的包:

    from selenium.common.exceptions import NoSuchElementException
    

    【讨论】:

    • 私人配置文件控制台返回仍然有相同的错误:公共配置文件私人配置文件 7646 27 符合条件的回溯(最近一次调用最后):文件“C:\Users\Desktop\Insta\Py-master.py” ,第 88 行,在
    【解决方案2】:

    您可以使用try... except 代替if... else。在你的情况下,它可能是:

    for follower in followers:
            #Iterate into the list
            browser.get(follower)
            sleep(2)
            try:
                browser.find_element_by_css_selector("li:nth-of-type(2) a.-nal3 span").get_attribute("title"):
                print("Public profil")
            except:
                print("private profil") 
                continue  
    

    【讨论】:

    • 我知道,但是except 的问题是在他到达私人档案后停止循环
    • 为什么它会停止循环?里面没有brake 所以它不应该
    • 我不知道为什么,也许他认为它应该在except 之后停止
    • 我刚刚编辑并添加了continue。你能试试吗?
    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 2021-05-03
    • 2012-07-20
    • 2020-05-30
    • 2021-04-05
    相关资源
    最近更新 更多