如何使用Selenium来获得停车价格?

时间:2016-01-28 19:08:07

标签: python selenium web web-scraping screen-scraping

我尝试使用网页抓取来获取此链接的停车价格https://application.parkbytext.com/accountus/prepay.htm?locationCode=1127。这一天 $ 2 是我想要获得的那一天。我使用的是python + selenium,但却无法获得停车价格。下面是我使用的代码,但有时我会点击目标,但大部分时间我都会收到错误

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"class name","selector":"gwt-RadioButton"}.

有人可以帮忙吗?提前谢谢

def downtownparking(driver):
driver.get("https://application.parkbytext.com/accountus/prepay.htm?locationCode=1127")
try:
    ### driver.wait = WebDriverWait(driver, 16)
    ### driver.implicitly_wait(20)
    cr = driver.find_element_by_class_name("gwt-RadioButton")
    dayprice = cr.find_element_by_tag_name("label")
    print (dayprice.text)

1 个答案:

答案 0 :(得分:1)

页面加载需要时间。目前webdriver试图找到一个元素,它还没有出现在DOM树中。添加Explicit Wait

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

cr = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, "gwt-RadioButton"))
)

另外,请注意,我会改用input的名称:

cr = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//input[@name='periodType']/following-sibling::label"))
)
print(cr.text)  # prints "Day - $2.00"