2016-01-23 127 views
-4

第一個問題:如何使python最小化chrome?Selenium NoSuchElementException with driver.find_element_by_xpath

第二個問題:當使用下一個按鈕進入最後一頁時如何告訴python繼續......而不是給我一個錯誤?

driver.get("https://www.google.com/#q=" + user_input) 
for n in range(5): 
    driver.find_element_by_xpath("""//*[@id="pnnext"]/span[2]""").click() 
    time.sleep(2) 
    posts2 = driver.find_elements_by_class_name("_Rm") 
    for post2 in posts2: 
     print(post2.text) 
     text_file.write(post2.text + "\n") 

執行此代碼我碰到下面的錯誤後:

Traceback (most recent call last): 
    File "C:/Users/Skid/PycharmProjects/untitled/2nd.py", line 20, in <module> 
    driver.find_element_by_xpath("""//*[@id="pnnext"]/span[2]""").click() 
    File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 258, in find_element_by_xpath 
    return self.find_element(by=By.XPATH, value=xpath) 
    File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 712, in find_element 
    {'using': by, 'value': value})['value'] 
    File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 201, in execute 
    self.error_handler.check_response(response) 
    File "C:\Users\Skid\AppData\Local\Programs\Python\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 181, in check_response 
    raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="pnnext"]/span[2]"} 
    (Session info: chrome=47.0.2526.111) 
    (Driver info: chromedriver=2.20.353145 (343b531d31eeb933ec778dbcf7081628a1396067),platform=Windows NT 10.0 x86_64) 
+0

你需要更具體。什麼是錯誤?你在哪裏得到它? – Guy

+0

@guy修好了對不起, – Nevermind123

+0

我想知道爲什麼人們反對,但他們沒有幫助! – Nevermind123

回答

1

你得到NoSuchElementException,司機無法找到你的元素。將您的xpath更改爲此

driver.find_element_by_xpath("//*[@id='pnnext']/span[2]").click() 

不帶3引號。

+0

錯誤:http://pastebin.com/Ykud1qPK – Nevermind123

+1

@ Nevermind123好吧,如果沒有我要求的html,我無法真正幫助你。 (並將其添加到您的問題作爲文本請,我沒有點擊鏈接)。 – Guy

+0

好的男人,我明天再問。這只是一個pastebin鏈接,但你可以稍後再問,或許是某種東西,可能只是自己修復它 – Nevermind123

相關問題