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

标签 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'元素当前不可见,因此可能无法与之交互';堆栈跟踪:

如何解决这个问题?

enter image description here

最佳答案

问题在于您正在查找该元素,但该元素尚不存在。 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()

关于python - 无法在 python 中使用 selenium webdriver 单击链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25811624/

相关文章:

python - Django 1.10 AdminDateWidget() 在ModelForm中的使用

python - 如何在 Python 中使用 OpenCV 检测行上方的文本

python-2.7 - 如何关闭 pocketsphinx-python 中的信息日志

java - Selenium |元素不可交互错误: Explored all the options of stack overflow

java - 我如何使用 Java 与 Selenium Webdriver 中的此输入框进行交互?

python - Django 过滤器未返回正确的结果

python - 如何使用 PyOpengl 或 pyglet 在桌面上绘制?

python - 使用 python 编写文本文件

Python无法识别请求 header 中的cookie

java - Selenium读取表并逐行写入文件