使用Python中的Selenium单击并查看更多页面

时间:2015-10-13 11:49:34

标签: python selenium xpath selenium-webdriver

问题 我需要使用Selenium进入此page中的所有顶级用户个人资料。 热门用户个人资料位于页面右侧。

我做了什么

    self.driver.get(response.url)
    user_list = self.driver.find_elements_by_xpath('//table[contains(@class,"W-100 Bc-c")]/tbody/tr')
    for single_user in user_list:
        single_user.find_element_by_xpath('.//td/a').click()
        time.sleep(3)

但我收到此错误消息:

  

WebDriverException:消息:未知错误:元素无法点击   在点(865,685)。其他元素将收到点击:

<div id="MouseoverMask" class="End-0 Start-0 T-0 B-0"></div>

信息 Python 2.7.10 硒2.48 Pycharm

修改+

我尝试打印名称并且有效:

   print(str( single_user.find_element_by_xpath('.//td/a').text ) )

但是点击()号。

2 个答案:

答案 0 :(得分:1)

如果您确定您获得的对象是正确的,通常问题是:

  • 该对象不可见
  • 当您尝试单击对象时,页面未完全加载。

所以,只需看看Selenium提供的Wait方法,确保您的对象可见

为了等待元素可点击:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID,'someid')))

在您的情况下,您可以尝试使用您获得的ID查找每个元素,然后单击它:

self.driver.get(response.url)
user_list = self.driver.find_elements_by_xpath('//table[contains(@class,"W-100 Bc-c")]/tbody/tr')
for single_user in user_list:
    id = single_user.find_element_by_xpath('.//td/a').get_attribute("id")
    self.driver.find_elements_by_id(id).click()
    time.sleep(3) 

答案 1 :(得分:0)

我没有看到任何错误,但在第一次点击网页元素 已更改 之后,您将无法获得之前捕获的下一个网络元素XPath的。顺便试试下面的代码 -

from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get('https://answers.yahoo.com/dir/index/discover?sid=396545663')
user_list = driver.find_elements_by_xpath('//table[contains(@class,"W-100 Bc-c")]/tbody/tr')
lnks = [i.find_element_by_xpath('.//td/a').get_attribute('href') for i in user_list]
for single_user in lnks:
    driver.get(single_user)
    time.sleep(3)