我试图单击“查看所有详细信息”按钮以从OpenTable扩展一家餐厅的详细信息,但我一直没有遇到任何例外。
from selenium import webdriver
driver = webdriver.Chrome(
'/Library/Python/2.7/site-packages/chromedriver')
url = "https://www.opentable.com/chicago-illinois-restaurant-listings"
driver.get(url)
element = driver.find_element_by_xpath(
'//*[@id="search_results"]/div[2]/div[1]/div/div[2]/div[1]/a')
element.click()
driver.find_element_by_css_selector(
'#overview-section > div:nth-child(4) > div.f9f46391 > button').click()
driver.quit()
答案 0 :(得分:1)
每个结果链接都具有target='_blank'
属性。这意味着如果单击链接详细信息页面,将在新选项卡中打开。要处理新标签上的元素,您应该切换到该标签:
driver.get(url)
current = driver.current_window_handle
driver.find_element_by_css_selector('a.rest-row-name').click()
driver.switch_to.window([tab for tab in driver.window_handles if tab != current][0])
请注意,您还应该等待按钮变为可点击状态:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//button[.="View all details"]'))).click()