'XPath syntax with multiple conditions
I'm new to Selenium and I'm not very familiar with coding, so any help would be much appreciated.
I'm trying to check item on website and have added first item to go to basket and proceed to checkout.
Everything works, but I need to add condition criteria, where sellers name or price is also checked, so let's say - if item is sold by Cody OR price is 200EUR - only then add to cart. (one condition or two of them match, then "add to cart" in other cases print("Item not available")
See attached picture of the store for reference
My code is:
from selenium.common.exceptions import NoSuchElementException
while (True):
try:
wd.get ("http://majasadrese.lv/test_adrese")
a_autoid_2_offer_1 = wd.find_element_by_xpath ('//*[@id="a-autoid-2-offer-1"]')
a_autoid_2_offer_1.click()
break
except NoSuchElementException:
print(“Item not available”)
time.sleep(10)
Where
a_autoid_2_offer_1 = wd.find_element_by_xpath ('//*[@id="a-autoid-2-offer-1"]')
a_autoid_2_offer_1.click()
is first "Add to cart" on top of the page in the screenshot.
Solution 1:[1]
Condition within a singe node
If we talk about a single node, it's simply
//*[(condition1) or (condition2)]
e.g.
//*[(@id="a-autoid-2-offer-1") or (text()="200EUR")]
Condition for multiple nodes
But if you like to check some conditions for multiple nodes, you have to
- Find the first node (node1) by condition1
- Go down/up or following/previous to another node(node2) by condition2
- Return back to the node1
Simple example
for this html
<div class="some-div-class active">
<a href="some-href-1">a1-text</a>
</div>
<div class="some-div-class">
<a href="some-href-1">a2-text</a>
</div>
...
this
//div[(contains(@class, 'some-div-class')) and (contains(@class, 'active'))]//a[starts-with(@href, 'some-href')]/..
will find the div with
- condition1: both classes
some-div-clas,active
and
- condition2: with a child
awithhrefstarted withsome-href
1. condition1 - node1
//div[(contains(@class, 'some-div-class')) and (contains(@class, 'active'))]
2. condition2 - node2
//a[starts-with(@href, 'some-href')]
3. return back to node1
/..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Max Daroshchanka |
