我正在尝试使用带有python代码的selenium web驱动程序对Amazon.com类别复选框进行测试,我尝试了几种方法,但我不知道如何选择Book类别的复选框,例如没有其id或名称。我使用了一些插件来获取正确的xpath,如XPath Helper for chrome和路径检查器在Firefox ...
这是我的代码,我的尝试被评论。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from time import sleep
import unittest
class Test_PythonOrg(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Firefox()
def tearDown(self):
sleep(4)
self.browser.close()
self.browser = None
def test_07_ListOfTodayDeals(self):
self.browser.get("http://www.amazon.com")
deals = self.browser.find_element_by_link_text("Today's Deals")
deals.click()
books = self.browser.find_element_by_id("widgetFilters")
books.find_element_by_xpath("/x:div[1]/x:div/x:span[8]/x:div/x:label/x:span").click()
#for i in range(20):
#try:
#self.browser.find_element_by_xpath(".//*[contains(text(), 'Books')]").click()
#break
#except NoSuchElementException as e:
#print('retry')
#time.sleep(1)
#else:
#print('Test Failed')
browser.close()
#sign_in_button = self.browser.find_element(By_XPATH,'(//input[@name=''])[8]')
#sign_in_button.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
#sleep(5)
#self.assertTrue("No results found." not in self.browser.page_source)
if __name__ == "__main__":
unittest.main(verbosity=2)
HTML
<span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="{"attribute":"whitelist_categories","value":"283155","rangeEnd":"","rangeStart":"","filterType":"checkboxes"}">
<div class="a-checkbox checkbox checked a-spacing-micro"><label><input name="" value="" checked="" type="checkbox"><i class="a-icon a-icon-checkbox"></i><span class="a-label a-checkbox-label">
Books
</span></label></div>
</span>
答案 0 :(得分:0)
我用一个非常简单的代码行使用正确的xpath解决了我的问题:
self.browser.find_element_by_xpath("(//input[@name=''])[8]").click()
它完美有效!
答案 1 :(得分:0)
我修改了你的代码,现在它正在运行
.MP4