Selenium Python - Finding div containing two specific elements
<p>I'm building a python script using selenium, and have ran into a quite confusing problem.</p>

<p>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.</p>

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

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

<p><strong>DOM:</strong></p>

<pre><code>&lt;div class="inner-article"&gt;
  &lt;h1&gt;
    &lt;a class="product-name"&gt;Silk Shirt&lt;/a&gt;
  &lt;/h1&gt;
  &lt;p&gt;
    &lt;a class="product-color"&gt;Black&lt;/a&gt;
  &lt;/p&gt;
&lt;/div&gt;
</code></pre>

<p><strong>What i've tried so far:</strong>
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. </p>

<p>How would i go about doing this?</p>

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

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

<p>To make it reusable:</p>

<pre><code>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))
</code></pre>

python css selenium selection