如何处理不存在的 DIV 标签。使用硒 & Python

what to do for non present DIV tag. Using Selenium & Python

我正在尝试借助 selenium 和 python 从此容器“PROJECT INFORMATION”中提取信息 //www.rera.mp.gov.in/view_project_details.php?id =aDRYYk82L2hhV0R0WHFDSnJRK3FYZz09 但是在这样做时我收到了这个错误

无法定位元素: {“方法”:“xpath”,“选择器”:“/html/body/div/article/div2/div/div2/div2/div2”}

研究后发现这个突出显示的div不见了,而且这个容器里有很多地方都没有div。我该怎么做?我只需要 table 右侧的信息

我的代码:

for c in [c for c in range(1, 13) if (c == True)]:            

    row = driver.find_element_by_xpath("/html/body/div/article/div[2]/div/div[2]/div["+ str(c) +"]/div[2]").text

    print(row, end="   ")
    print("     ")
else:
    print('NoN')

错误:

no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/article/div[2]/div/div[2]/div[2]/div[2]"}
  (Session info: chrome=83.0.4103.106)

突出显示的字段是两种不同的情况。对于“注册号”,所需的 div 不存在,对于“建议的结束日期”,它存在但仅包含白色 space.

试试这个而不是 for c... 循环。它应该处理这两种情况。

#find parent element
proj_info=driver.find_element_by_xpath("//div[@class='col-md-12 box']")

#find all rows in parent element
proj_info_rows = proj_info.find_elements_by_class_name('row')

for row in proj_info_rows:
    try:
        if row.find_element_by_class_name('col-md-8').text.strip() == "":
            print(f"{row.find_element_by_class_name('col-md-4').text} contains only whitespace {row.find_element_by_class_name('col-md-8').text}")
            print('NaN')
        else:
            print(row.find_element_by_class_name('col-md-8').text)
    except SE.NoSuchElementException:
        print('NaN')

您需要导入:

from selenium.common import exceptions as SE