单击图像链接-Selenium / Python

时间:2019-12-30 20:43:20

标签: python selenium

试图建立一个网络爬虫,但是为了我的生命,我似乎无法点击此链接。无论尝试如何,我总是会收到“无法定位元素”错误。这是HTML:

<td colspan="2" width="100" height="100">
<a href="place.php?whichplace=desertbeach">
<img src="https://s3.amazonaws.com/images.kingdomofloathing.com/otherimages/main/map7beach.gif" alt="Desert Beach" title="Desert Beach" width="100" height="100" border="0">
</a>
</td>

我正在尝试单击与a href链接关联的链接。尝试通过css,xpath等来查找元素,但是似乎找不到任何元素。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

要单击链接,请诱导WebDriverWaitelement_to_be_clickable()并跟随CSS选择器。

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[href="place.php?whichplace=desertbeach"]'))).click()

或XPATH

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//a[@href="place.php?whichplace=desertbeach"]'))).click()

您需要导入以下库。

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

更新


该表位于其中,并且iframe需要首先切换它才能单击该元素。生成WebDriverWait()和frame_to_be_available_and_switch_to_it()并使用css选择器。

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, 'frame[src="main.php"]')))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[href="place.php?whichplace=desertbeach"]'))).click()