Python+硒。找不到elemen

2024-04-26 00:07:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用Python和selenium实现了这个脚本来点击广告。 但现在这个脚本不起作用了。 在页面上找不到元素。 请帮我改一下剧本。谢谢您! enter image description here

from selenium import webdriver
import time
browser=webdriver.Firefox()
browser.get('http://rutracker.ignn.ru')
browser.switch_to_frame(browser.find_element_by_xpath('//iframe[starts-with(@class,"tblock_")]'))
browser.find_element_by_xpath("//a[contains(@href,'tmozs.com')]").click()
time.sleep(10)
browser.quit()

Tags: fromimportbrowser脚本元素bytimeselenium
2条回答

您可以尝试等待一段时间,直到required iframe出现在DOM中,然后切换到它:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

wait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it(browser.find_element_by_xpath('//iframe[contains(@src, "//tmozs.com/")]')))

以下是您问题的答案:

您可以使用下面的代码块单击左上角的广告:

I have exclusively used time.sleep() to reduce the time in preparing this solution. All the time.sleep() can be replaced by Explicit Wait

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import time

binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
driver.get('http://rutracker.ignn.ru')
time.sleep(5)
driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'tmozs.com/jsonp.php')]"))
time.sleep(5)
driver.find_element_by_xpath("//div[@class='feed-inner']/div[@class='feed-cell'][1]/a[@class='feed-cell-inner']/div[@class='teaser']/table[@class='teaser-inner']//img[contains(@src,'in.ogoyj.com')]").click()
time.sleep(5)
driver.quit()

如果这回答了你的问题,请告诉我。在

相关问题 更多 >