如何使用 selenium 从 html 中提取列表,然后在 python 脚本中使用它来查找元素

How to extract a list from html with selenium and then use it in python script to find elements

我正在尝试使用 selenium 和 python 从网页中提取列表。我需要将其作为列表导入,以便稍后使用 python 代码在该列表中查找元素。

这是它在网页中的存储方式:

...<input type="hidden" name="GridContainerDataV" value="[["7131090","Arvejas, Enteras Verdes","400","",""],["71311099","Arvejas, Enteras Azules","520","abril/2021","mayo/2021"],["71311100","lo que sea","720","junio/2021","diciembre/2021"],...]]" autocomplete="off">

这就是我尝试提取的方式(我是 python 中的超级初学者):

try:
    tabla = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, "GridContainerDataV")))
    print(tabla.value)

榜单:

[["7131090","Arvejas, Enteras Verdes","400","",""],["71311099","Arvejas, Enteras Azules","520","abril/2021","mayo/2021"],["71311100","lo que sea","720","junio/2021","diciembre/2021"],...]]

<input>标签的value属性的并且是隐藏。要提取列表,您需要引入 for the presence_of_element_located() and you can use either of the following :

  • 使用NAME:

    print(WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.NAME, "GridContainerDataV"))).get_attribute("value"))
    
  • 使用CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='GridContainerDataV']"))).get_attribute("value"))
    
  • 使用XPATH:

    print(WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//input[@name='GridContainerDataV']"))).get_attribute("value"))
    
  • 注意:您必须添加以下导入:

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

你应该使用get_attribute函数

try:
    tabla = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "GridContainerDataV")))
    print(tabla.get_attribute('value')