简体   繁体   中英

Selenium Python - Product array page, how do dynamically click a product

saksoff5th.com is the site URL that i am using. I search via text "Belts" on the home page and then click Men link. This takes me to the product array page of men's belt. I want to click the 2nd product on the array, but i am getting error.

The code i am using is. Here in i am trying to put all of those in a list and then click the second product on the page.

elemprodcl = browser.find_element_by_id('search-result-items')
Listprdcl= elemprodcl.find_elements_by_class_name('grid-tile')
elemprodcl2 = Listprdcl[1].find_element_by_class_name('product-tile')
elemprodcl3 = elemprodcl2.find_element_by_class_name('product-image')
elemprodcl4 = elemprodcl3.find_element_by_tag_name('a').click() 

Error received as :-

Traceback (most recent call last):
  File "C:\Python27\Off5th_Guest_Checkout", line 39, in <module>
    elemprodcl4 = elemprodcl3.find_element_by_tag_name('a').click()
  File "C:\Python27\lib\selenium\webdriver\remote\webelement.py", line 59, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Python27\lib\selenium\webdriver\remote\webelement.py", line 369, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\selenium\webdriver\remote\webdriver.py", line 164, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\selenium\webdriver\remote\errorhandler.py", line 164, in check_response
    raise exception_class(message, screen, stacktrace)
ElementNotVisibleException: Message: u'Element is not currently visible and so may not be interacted with' ; Stacktrace: 

Well you were nearly there. You were trying to click the a Web element, where as you should try to click the img .

So continuing from where you left off :

elemprodcl4 = elemprodcl3.find_element_by_tag_name('a')
elemprodcl4.find_element_by_tag_name('img').click()

or simply by using a single CSS selector:

browser.find_element_by_css_selector('.search-result-items li:nth-child(2) div > div > a').click()

Explanation of the css selector syntax-

  • .search-result-items is the class name as the text is preceded by a dot.
  • li is the descendant(child) of the above class. and the nth-child indicates which child from the list (array) of children do we want to select
  • Similar for div and a , they are children of the preceding selector mentioned

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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