繁体   English   中英

Python Selenium找不到CSS元素

[英]Python selenium didn't find css element

我从python中的Selenium Ide导入了代码。 硒测试可以正常工作,而无需单击该项目,并且可以无缝滚动单击某个项目。 HTML硒代码:

    <?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)

我在不同的硒定位器和xpath css中进行了测试,它可以工作,但是在python中没有滚动,单击该元素不起作用。

首先,您可以等待该元素变得可见

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()

并且,如果您需要在单击之前滚动到该元素,请使用操作链

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()

并且,如果需要, 滚动到该元素的视图

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM