代码之家  ›  专栏  ›  技术社区  ›  nestlejscrunch

如何使用python遍历xml路径字符串(表行-tr[1]、tr[2]、tr[3]…)?

  •  -1
  • nestlejscrunch  · 技术社区  · 6 年前

    我有这个html xml路径:

    "//*[@id="example"]/tbody/tr[2]/td[1]"
    

    它必须通过find_element()算法作为字符串处理 但是我需要在tr[2]处迭代(例如,tr[2]、tr[3]、tr[4]…),这样我的WebScraping算法就可以在HTML表中展开一个可点击的按钮。

    有哪些策略/实现可以实现这一点?

    (我使用selenium python库作为webscraper)

    2 回复  |  直到 6 年前
        1
  •  0
  •   Raj    6 年前

    可以使用以下代码获取所有所需元素(行)的集合:

    driver.find_elements_by_xpath("//*[@id="example"]/tbody//tr/td[1]");
    

    然后可以遍历元素集合并执行所需的操作。

        2
  •  0
  •   cruisepandey    6 年前

    如果你想绕过去,

    让xpath像这样动态:

    我想你有5排。

    for i in range(5):
     driver.find_element_by_xpath("//*[@id="example"]/tbody/tr['"+i+"']/td[1]").click()   
    

    或者使用webdriverwait,它将是:

    wait = WebDriverWait(driver,30)
    
    for i in range(5): 
      wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id="example"]/tbody/tr['"+i+"']/td[1]"))).click()  
    

    请注意,如果您需要导入这些:

    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC