无法在python中使用selenium webdriver单击链接

时间:2014-09-12 15:20:33

标签: python python-2.7 selenium selenium-webdriver web-scraping

我想点击下面显示的链接:

<a class="user" href="/Kevin-Rose" action_mousedown="UserLinkClickthrough" id="__w2_L73qRYl_link" 
target="_blank">
         <span class="matched_term">Kevin Rose</span>
</a>

我尝试使用以下代码:

 user = driver.find_element_by_xpath("//a[@class='user'][1]")
 user.click()

我收到了以下错误:

ElementNotVisibleException:消息:u&#39;元素当前不可见,因此可能无法与&#39;进行交互。 ;堆栈跟踪:

我该如何解决这个问题?

enter image description here

2 个答案:

答案 0 :(得分:1)

问题是你找到了元素,而它尚未存在。 Wait为此。

以下是完整的代码,从登录,搜索到关注第一个Kevin Rose链接:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


URL = "http://www.quora.com"
EMAIL = 'your email here'
PASSWORD = 'your password here'

driver = webdriver.Chrome()  # can be webdriver.Firefox() in your case
driver.get(URL)
wait = WebDriverWait(driver, 10)

# login
form = driver.find_element_by_class_name('regular_login')
username = form.find_element_by_name('email')
username.send_keys(EMAIL)

password = form.find_element_by_name('password')
password.send_keys(PASSWORD)

login_button = form.find_element_by_xpath('//input[@type="submit" and @value="Login"]')
login_button.click()

# search
search = wait.until(EC.presence_of_element_located((By.XPATH, "//form[@name='search_form']//input[@name='search_input']")))
search.send_keys('Kevin Rose')
search.send_keys(Keys.ENTER)

# follow the link
link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Kevin Rose")))
link.click()

答案 1 :(得分:0)

尝试使用以下定位器

Xpath : "//span[text()='Kevin Rose']"

cssSelector : "a[href*='Kevin-Rose'] > span"

修改-I

这是点击个人资料名称Kevin Rose

的Xpath
"//div[contains(.,'Profile:') and contains(@class,'photo')]/span/a//span[text()='Kevin Rose']"