0


selenium.common.exceptions.NoSuchElementException

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element

最近刚刚学习爬虫,遇到了这个问题,上网找了很多方法,比如因为iframe啊,网站没有加载出来需要使用sleep啊,或者使用隐式等待啊。后来还下载了chropath(这是一个抓取xpath路径的插件,详情请自己百度。),但是都没有解决问题。

后来我发现,因为我写的爬虫需要登录,登录之后是另一个网页(窗口),然而在selenium眼中,新窗口默认是不切换过来的。所以需要使用switch_to.window,如下:

web=webdriver.Edge()
web.implicitly_wait(10)
web.get('https://www.jd.com/')
while True:
    if web.find_element(By.LINK_TEXT,'你好,请登录'):
        web.find_element(By.LINK_TEXT,'你好,请登录').click()
        time.sleep(10)
        break
time.sleep(2)
# 点击购物车
while True:
    if web.find_element(By.XPATH,'//*[@id="settleup"]/div[1]/a'):
        web.find_element(By.XPATH,'//*[@id="settleup"]/div[1]/a').click()
        break
web.switch_to.window(web.window_handles[-1])# 这里的-1表示selenium切换到第几个窗口。
time.sleep(2)
# 全选
while True:
    if web.find_element(By.XPATH,'//*[@id="cart-body"]/div[2]/div[3]/div[1]/div'):
        web.find_element(By.XPATH,'//*[@id="cart-body"]/div[2]/div[3]/div[1]/div').click()
        break

虽然这个问题很简单,但是我还是花了不少时间,所以写出来希望帮助像我一样的小白避坑。


本文转载自: https://blog.csdn.net/weixin_45927370/article/details/129279884
版权归原作者 weixin_45927370 所有, 如有侵权,请联系我们删除。

“selenium.common.exceptions.NoSuchElementException”的评论:

还没有评论