【问题标题】:If element does not exist, continue the job anyway try: except NoSuchElementException: pass如果元素不存在,则继续工作尝试:除了 NoSuchElementException:通过
【发布时间】:2017-10-26 16:22:25
【问题描述】:

如果没有找到此site 的元素,我正在尝试继续工作: 我试过使用:

try:
except NoSuchElementException:
    pass

以及if then 语句。但是,前一种方法不起作用,如果那样的话,方法似乎很容易崩溃。 我选择了这个page,上面没有文字,看看它如何处理不存在元素的页面。

try:
    # Team ODDS
    time.sleep(4)
    clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ('.brdSports td td tr:nth-child(1) .sport-namerow .left'))))
    langs = driver.find_elements_by_css_selector(".brdSports td td tr:nth-child(1) .sport-namerow .left")
    #tbody > tr > td > table > tbody > tr: eq(1) > td > table > tbody > tr > td > table > tbody > tr > td:eq(1) > table > tbody > tr: eq(0) > td > table > tbody > tr > td > table > tbody > tr > td:eq(0) > div > div
    langs_text = []

    for lang in langs:
        print(lang.text)
        langs_text.append(lang.text)

    time.sleep(0)
    time.sleep(4)
    # BACK TEAM
    #langs1 = driver.find_elements_by_xpath("//ul[@class='runners']//li[2]")
    clickMe = wait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ('.brdSports td td tr:nth-child(1) .sport-namerow .txtBld'))))
    langs1 = driver.find_elements_by_css_selector(".brdSports td td tr:nth-child(1) .sport-namerow .txtBld")
    langs1_text = []

    for lang in langs1:
        print(lang.text)
        langs1_text.append(lang.text)

    url1 = driver.current_url

    time.sleep(0)

    with open('vtg12.csv', 'a', newline='', encoding="utf-8") as outfile:
        writer = csv.writer(outfile)
        for row in zip(langs_text, langs1_text):
            writer.writerow(row + (url,))
            print(row + (url,))
except NoSuchElementException:
    pass

完整的code

【问题讨论】:

  • 当您使用except NoSuchElementException 时究竟会发生什么?
  • @BenWurth 对我来说,我仍然有错误。我得到了: Traceback(最近一次通话最后):文件“C:/Users/Bain3/PycharmProjects/untitled4/centa testing.py”,第 1785 行,在 clickMe = wait(driver, 10).until(EC. element_to_be_clickable((By.CSS_SELECTOR, ('.brdSports td td tr:nth-child(1) .sport-namerow .left')))) 文件“C:\Users\Bain3\Anaconda3\lib\site-packages\selenium \webdriver\support\wait.py",第 80 行,直到引发 TimeoutException(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message:
  • 看起来你需要为 Selenium 的 TimeoutException 增加一个 except 子句。
  • @BenWurth 你能举例说明如何做到这一点
  • @BenWurth HMMM.. 除了 TimeoutException 如 ex: 可能有效.. 做进一步的测试。是的,很确定现在可以工作了,太棒了!

标签: python python-3.x selenium selenium-webdriver web-scraping


【解决方案1】:

根据您在 cmets 中发布的 stacktrace,您需要为 Selenium 的 TimeoutException 添加一个额外的异常。

这应该可行:

except TimeoutException:
    pass

【讨论】:

  • 这适用于单个页面,但我正在尝试循环浏览一系列页面:pastebin.com/WymkYUs4
  • try except 放在for 循环内,以便在每个循环中检查它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 2022-11-01
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
相关资源
最近更新 更多