所以我知道我找到了正确的元素。我已经尝试使用xpath和css选择器,两者都正确检索正确的按钮。
然后,当我在按钮上拨打.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')
这是元素的图片
答案 0 :(得分:1)
首先,由于您使用的是PhantomJS
,假装不是PhantomJS
可能会解决问题,请参阅此文章,其中包含有效的Python / Selenium示例:
并确保您单击要检查的同一按钮。可以有多个"关注"页面上的按钮。
此外,添加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。
答案 1 :(得分:0)
我通过从PhantomJS驱动程序切换到chromedriver来实现它。