from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
driver.get("http://en.savefrom.net/")
elem = driver.find_element_by_id("sf_url")
elem.clear()
elem.send_keys("https://www.youtube.com/watch?v=0BQdUrsDegM&index=1&list=PLUY1lsOTtPeJNBuSweXS9pcSKbP4mr32S")
elem.send_keys(Keys.RETURN)
time.sleep(5)
elem.find_element_by_id('sf_frame')
错误:
D:\Anaconda2\python.exe C:/Users/Administrator/PycharmProjects/untitled3/selenium-test.py Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/untitled3/selenium-test.py", line 14, inelem.find_element_by_id('sf_frame') File "D:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webelement.py", line 138, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "D:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webelement.py", line 478, in find_element {"using": by, "value": value})['value'] File "D:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webelement.py", line 461, in _execute return self._parent.execute(command, params) File "D:\Anaconda2\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "D:\Anaconda2\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element (Session info: chrome=51.0.2704.103) (Driver info: chromedriver=2.7.236900,platform=Windows NT 6.1 SP1 x86)
找不到元素就只要两个原因:
1.元素是否已加载。 # 等待直到元素出现, 点击 def waitClick(self, time, element): try: print('元素加载, 页面等待中 ...') WebDriverWait(self.browser, time).until(EC.presence_of_element_located(element)) self.browser.find_element(*element) except Exception,e: print('元素异常, 页面已截图 :') self.screenshot() 2.匹配是否写对。