繁体   English   中英

如何点击带有图片的onclick链接? Python Selenium

[英]How to click on onclick link with image? Python Selenium

我只是在学习如何在Python中使用Selenium动态进行网络抓取。 我目前正在尝试点击网页上的链接,以在搜索结果上进行分页。

到目前为止,这是我正在使用的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome('C:\\Users\\km13\\chromedriver.exe')
driver.get("http://www.congreso.gob.pe/pley-2016-2021")
elem = driver.find_element_by_css_selector("img[src='/Sicr/TraDocEstProc/CLProLey2016.nsf/8eac1ef603908b5105256cdf006c41b1/$Body/0.AB2?OpenElement&FieldElemFormat=gif']")
elem.click()

这是与我要单击的元素相对应的HTML:

 `<a href="" onclick="return _doClick('05257FB7005EB655.8eac1ef603908b5105256cdf006c41b1/$Body/0.A50', this, null)"><img src="/Sicr/TraDocEstProc/CLProLey2016.nsf/8eac1ef603908b5105256cdf006c41b1/$Body/0.AB2?OpenElement&amp;FieldElemFormat=gif" width="81" height="16" border="0"></a>`

从我对HTML的有限了解来看,似乎该链接实际上嵌入在gif中,这就是为什么我尝试使用与该图像一起显示的CSS选择器的原因。 但这没有用。

任何指导将不胜感激!

更新:我通过添加以下导入更改了代码

from selenium.webdriver.common.by import By

我更改了以下内容:

elem = driver.find_element(By.CSS_SELECTOR, "img[src='/Sicr/TraDocEstProc/CLProLey2016.nsf/8eac1ef603908b5105256cdf006c41b1/$Body/0.AB2?OpenElement&amp;FieldElemFormat=gif']")
elem.click()

现在,我收到“没有这样的元素”的错误消息。

有一个iframe。您需要先切换到iframe才能访问元素。请尝试以下代码。使用WebDriverWait处理动态元素。

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

driver = webdriver.Chrome('C:\\Users\\km13\\chromedriver.exe')
driver.get("http://www.congreso.gob.pe/pley-2016-2021")

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.NAME, 'ventana02')))
elem = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(
    (By.XPATH, "//a[contains(@onclick,'A50')]/img[contains(@src,'Sicr/TraDocEstProc/CLProLey')]")))
elem.click()

已编辑

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
driver = webdriver.Chrome('C:\\Users\\km13\\chromedriver.exe')
driver.get("http://www.congreso.gob.pe/pley-2016-2021")
driver.switch_to.frame(0)
elem=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//a[contains(@onclick,'A50')]/img[contains(@src,'Sicr/TraDocEstProc/CLProLey')]")))
elem.click()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM