2016-12-15 20 views
0

所以我知道我正在找到正確的元素。我用xpath和css選擇器試過,都正確地檢索正確的按鈕。爲什麼python的selenium button.click()工作在twitter按鈕上?

然後當我打電話.click()上的按鈕,它不遵循該帳戶。

button = self.driver.find_element(By.CSS_SELECTOR, ".user-actions-follow-button.js-follow-btn.follow-button.btn") 
print(button.text) 
button.click() 
print('should have followed') 

有沒有人知道它爲什麼會這樣?

編輯: 這裏是整個類代碼:

class Scraper: 
    def __init__(self): 
     self.driver = webdriver.PhantomJS(executable_path='phantomjs') 
     self.loggedIn = False; 


    def login(self, url, username, password): 
     self.driver.get(url) 

     try: 
      usernameTextField = self.driver.find_element_by_css_selector(".js-username-field.email-input.js-initial-focus") 

      passwordTextField = self.driver.find_element_by_css_selector('.js-password-field') 

      usernameTextField.send_keys(username) 
      passwordTextField.send_keys(password + '\n') 
     except: 
      print('Already logged in') 

     try: 
      WebDriverWait(self.driver, 10).until(
        EC.presence_of_element_located((By.ID, 'dashboard-profile-prompt')) 
      ) 

     except: 
      self.loggedIn = False 

     finally: 
      print('succesfully logged in') 
      self.loggedIn = True 

    def followByUrl(self, url): 
     if self.loggedIn: 
      self.driver.get(url) 

      actions = ActionChains(self.driver) 
      wait = WebDriverWait(self.driver, 10) 
      follow = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".user-actions-follow-button.js-follow-btn.follow-button.btn"))) 


      print(follow.text) 

      actions.move_to_element(follow).click().perform() 

      print('should have followed') 

而這裏的元素

enter image description here

+0

你有什麼錯誤?一個'Element not visible'錯誤提示該元素尚未加載,並且在動態加載的頁面上很常見。 – theeastcoastwest

+0

@Frank沒有得到任何錯誤。它也正確地打印出按鈕。文字 – joe

+0

通常當我遇到這種問題時,它意味着錯誤的元素正在接收該動作。 – theeastcoastwest

回答

1

首先的圖片,因爲你正在使用PhantomJS,假裝沒被PhantomJS可能會解決這個問題,看到這個帖子有一個工作的Python /硒樣品:

而且,要確保你點擊你正在檢查被點擊相同的按鈕。頁面上可以有多個「關注」按鈕。

此外,添加一個Explicit Wait等待按鈕變爲可點擊:

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

wait = WebDriverWait(driver, 10) 

follow = wait.until(element_to_be_clickable((By.CSS_SELECTOR, "button.follow-button"))) 
follow.click() 

你也可以嘗試移動到元素,然後點擊通過"ActionChains"

from selenium.webdriver import ActionChains 

actions = ActionChains(driver) 
actions.move_to_element(follow).click().perform() 

或者,你可以點擊"via JavaScript"

driver.execute_script("arguments[0].click();", follow) 

而且不要忘了留在法律方面,遵循使用條款,是一個good web-scraping citizen

+0

嘗試了一切,仍然沒有任何工作。你認爲Twitter可能會檢測到請求來自機器人嗎? – joe

+0

@joe懷疑所以,儘管你必須遵守規則,以保持事物的法律方面。你使用什麼瀏覽器?您能否顯示迄今爲止的完整代碼?謝謝。 – alecxe

+0

我正在使用PhantomJS,到目前爲止我的整個班級編輯 – joe

0

我得到了它從PhantomJS司機chromedriver切換工作。

相關問題