Python selenium没有找到css元素

时间:2015-12-23 15:06:36

标签: python html css selenium xpath

我在python中从Selenium Ide导入了代码。硒测试工作正常,没有点击项目并滚动无缝点击项目。 HTML selenium代码:

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://www.amazon.com/" />
<title>New Test</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">New Test</td></tr>
</thead><tbody>
<tr>
    <td>open</td>
    <td>/</td>
    <td></td>
</tr>
<tr>
    <td>clickAndWait</td>
    <td>css=[alt=&quot;Deals in Books&quot;]</td>
    <td></td>
</tr>

</tbody></table>
</body>
</html>

但是在你滚动点击到想要的项目之前,Python不起作用。

from selenium import webdriver
import unittest, time, re

class Untitled(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "http://www.amazon.com/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_untitled(self):
        driver = self.driver
        driver.get(self.base_url)
        driver.find_element_by_css_selector("a.feed-carousel-control.feed-right > span.gw-icon.feed-arrow").click()
        driver.find_element_by_css_selector("a.feed-carousel-control.feed-right > span.gw-icon.feed-arrow").click()
        driver.find_element_by_css_selector("a.feed-carousel-control.feed-right > span.gw-icon.feed-arrow").click()
        driver.find_element_by_css_selector("a.feed-carousel-control.feed-right > span.gw-icon.feed-arrow").click()
        driver.find_element_by_css_selector("[alt=\"Deals in Books\"]").click()

  def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

我在不同的selenium定位器和xpath css中测试过它可以工作,但是在没有滚动的python中点击该元素是行不通的。

1 个答案:

答案 0 :(得分:0)

首先,您可以wait for the element to become visible

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

element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, "[alt=\"Deals in Books\"]"))
)
element.click()

并且,如果您需要在点击之前滚动到该元素,请使用Action Chains

deals_in_books = driver.find_element_by_css_selector("[alt=\"Deals in Books\"]")

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

如果需要,scroll into view of the element

browser.execute_script("arguments[0].scrollIntoView();", deals_in_books)