使用selenium和python提取不带任何类和id的div标记

2024-05-13 02:58:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从使用selenium的网站获取每小时和每天的水位数据。在

到目前为止我的代码

import time 
from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome(r"C:\Python27\chromedriver.exe")
driver.get('http://hydrology.gov.np/#/basin/77?_k=1r1onx')
time.sleep(5)
driver.find_elements_by_xpath("//*[contains(text(), 'Hourly')]").click()

但它不起作用。我不熟悉硒。我也尝试过其他方法来寻找元素,但没有成功。我将非常感谢在这方面的任何帮助。在

html中的代码

^{pr2}$

Tags: 数据代码fromimportuisupporttime网站
2条回答

//div[contains(text(),'Hourly')]根据HTML,您的xpath似乎是正确的,请与调试器联系,您将跟踪问题所在

可以通过三种方式单击元素:

  1. 在驱动程序。单击()
  2. 动作点击

    from selenium.webdriver.common.action_chains import ActionChains
    targetElement = driver.find_element_by_xpath("//div[contains(text(),'Hourly')]")
    actions = ActionChains(driver)
    actions.move_to_element(targetElement).click().perform()

  3. javascript执行器单击

    driver.execute_script("arguments[0].click();", element)

这个

driver.find_elements_by_xpath("//*[contains(text(), 'Hourly')]").click()

使用find_elements将返回元素列表。您必须在列表中迭代以单击它们。在

要获取每小时的数据,需要将这行替换为

^{pr2}$

这会给数据

Jun 18, 2018 6:00 AM 1.94 -0.15 0.89
Mon, Jun 18, 2018 7:00 AM 1.93 1.92 1.93
Mon, Jun 18, 2018 8:00 AM 1.91 1.91 1.91
Mon, Jun 18, 2018 9:00 AM 1.9 1.89 1.89
Mon, Jun 18, 2018 10:00 AM 1.88 1.88 1.88
Mon, Jun 18, 2018 11:00 AM 1.87 1.87 1.87
Mon, Jun 18, 2018 12:00 PM 1.88 1.88 1.88
Mon, Jun 18, 2018 1:00 PM 1.88 1.87 1.88
Mon, Jun 18, 2018 2:00 PM 1.84 1.84 1.84
Mon, Jun 18, 2018 3:00 PM 1.86 1.84 1.85
Mon, Jun 18, 2018 4:00 PM 1.77 1.77 1.77
Mon, Jun 18, 2018 5:00 PM 1.68 1.68 1.68
Mon, Jun 18, 2018 6:00 PM 1.63 1.62 1.62
Mon, Jun 18, 2018 7:00 PM 1.62 1.62 1.62

相关问题 更多 >