【问题标题】:How to click the call drop down using selenium webdriver python?如何使用 selenium webdriver python 单击调用下拉菜单?
【发布时间】:2026-01-08 19:20:02
【问题描述】:
我无法使用 xpath 或 css 选择器单击呼叫下拉菜单并抓取电话号码。有什么办法吗?
driver=set_options_driver(headless=False)
driver.get('https://www.yellowpages.ca/bus/Ontario/Maidstone/CSR-Coxon-s-Sales-Rentals-Ltd/7222758.html?what=Rajic-Holdings-Inc&where=Maidstone+ON&useContext=true')
yp_name=[k.text for k in driver.find_elements_by_xpath("//div[@class='merchant__info--root ']//div[@class='merchant__name']")]
yp_addr=[k.text for k in driver.find_elements_by_xpath("//div[@class='merchant__info--root ']//div[@class='merchant__item merchant__address merchant__address__mobile']")]
try:
#driver.find_element_by_xpath("//div[@class='merchant__info-content']//span[@class='ypicon ypicon-phone mlr__icon']").click()
driver.find_element_by_xpath("//ul[@class='mlr mlr--merchant']//span[@class='ypicon ypicon-phone mlr__icon']").click()
yp_phone=driver.find_element_by_xpath("//li[@class='mlr__item mlr__item--more mlr__item--phone mlr__item--active isActive']//span[@class='mlr__sub-text']").text
except:
yp_phone=" "
【问题讨论】:
标签:
python
selenium
xpath
css-selectors
webdriverwait
【解决方案1】:
要单击文本为 Call 与下拉列表相关联的元素,您必须诱导 WebDriverWait 以使 元素可点击 并且您可以使用以下任一解决方案:
-
使用CSS_SELECTOR:
driver.get("https://www.yellowpages.ca/bus/Ontario/Maidstone/CSR-Coxon-s-Sales-Rentals-Ltd/7222758.html?what=Rajic-Holdings-Inc&where=Maidstone+ON&useContext=true")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div.merchant__info--root span.ypicon.ypicon-phone.mlr__icon"))).click()
-
使用XPATH:
driver.get("https://www.yellowpages.ca/bus/Ontario/Maidstone/CSR-Coxon-s-Sales-Rentals-Ltd/7222758.html?what=Rajic-Holdings-Inc&where=Maidstone+ON&useContext=true")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='merchant__info--root ']//span[@class='ypicon ypicon-phone mlr__icon']"))).click()
-
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
浏览器快照:
【解决方案2】:
您可以尝试点击下面给出的锚标记,而不是点击 span 元素。
driver.find_element_by_xpath("//ul[@class='mlr mlr--merchant']/li/a").click