Reputation: 799
I'm trying to select by xpath on products from this site https://www.crateandbarrel.ca/lindstrom-48x84-grey-curtain-panel/s557728
The xpaths look like this //*[@id="react_0HM7S1A7EGQ26"]/div/div/div[2]/div[4]/div[1]/div/div[2]/span/span/span
and CSS selectors like this #react_0HM7S1A7EGQ26 > div > div > div.product-row.full-width > div.right-col > div.hidden-xs > div > div.shop-bar-price-area.jsProductPrice > span > span > span
The react_0HM7S1A7EGQ26
part is different on many products and I'm looking for a way to handle this.
Currently I'm doing something like this:
xpath = '//*[@id="react_0HM7S1A7EGQ26"]/div/div/div[2]/div[4]/div[1]/div/div[2]/span/span/span'
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath))).text
However this xpath cannot be used for all products because the 0HM7S1A7EGQ26
changes.
Upvotes: 0
Views: 426
Reputation: 25714
It's really not a good idea to use that large of an XPath or CSS selector. If the site changes at all the larger the locator, the more likely it will be that your locator will break.
It looks like you're trying to get the price
<div class="shop-bar-price-area jsProductPrice">
<span>
<span class="reg">
<span class="regPrice">CAD 74.95</span>
</span>
</span>
</div>
You can get the price using a simple CSS selector, span.regPrice
. The problem is that there are a TON of prices on the page for some reason... all of which are hidden except one. So to fix this, we can add code to use that locator and filter down to only the price that is visible.
prices = driver.find_elements_by_css_selector("span.regPrice")
displayed_price = list(filter(lambda x: x.is_displayed(), prices))
print(displayed_price.text)
If you don't want to use all that, from my inspecting that one provided page it looks like the visible price is always the second element. You could try this and see if it works on all products you care about.
prices = driver.find_elements_by_css_selector("span.regPrice")
print(prices[1].text)
Upvotes: 1
Reputation: 1836
Firstly, I am not able to find which element you are searching for in the website.
Regarding Xpath
you can use contains
method like this -
xpath = //*[contains(@id,"react_")]/div/div/div[2]/div[4]/div[1]/div/div[2]/span/span/span
Do let me know if it helps.
Upvotes: 0
Reputation: 547
Try to check id
few times, but looks like the react_
part is immutable.
So you can simply catch it by partial id:
"//*[contains(@id, "react_")]"
Upvotes: 0