0

I'm building a python script using selenium, and have ran into a quite confusing problem.

The website lists products using a name, which is not unique, and a color, which is not unique either. The color and name elements have the same parent.

My script gets user input on which product he wants the script to buy for him, and which color.

The problem: I can't for the life of me figure out how to select the right product using the two variables productName and productColor.

DOM:

<div class="inner-article">
  <h1>
    <a class="product-name">Silk Shirt</a>
  </h1>
  <p>
    <a class="product-color">Black</a>
  </p>
</div>

What i've tried so far: Obviously, selecting the first product named Silk Shirt on the page is quite easy. I considered selecting the first product, then selecting that products parent, selecting that elements parent, then selecting that parents second child, checking if it was black, and proceeding, but CSS doesn't have a parent selector.

How would i go about doing this?

0

2 Answers 2

1

Create a main loop that selects each div class="inner-article" element.

In the loop, look for elements that have an h1 child element and an a class=product-name grandchild element with text of "Silk Shirt", and a p child element and a a class=product-color grandchild element with text of "Black".

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, good idea. It's very important that the script runs as fast as possible. Do you think that this will slow the script down more than a second or two?
No, I wouldn't think so. (But.. how many products will be on a page?)
20 to 30, so it hopefully won't be a problem. Thanks a ton for taking the time to help me!
0

Perhaps try searching using xpath. The xpath below will return the div element that contains the product and color you desire.

driver.find_element_by_xpath('//div[@class="inner-article"][.//a[@class="product-name"][.="Silk Shirt"]][.//a[@class="product-color"][.="Black"]]')

To make it reusable:

def select_product(name, color):
    return driver.find_element_by_xpath('//div[@class="inner-article"][.//a[@class="product-name"][.="{product_name}"]][.//a[@class="product-color"][.="{product_color}"]]'.format(product_name=name, product_color=color))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.