So I want to select an element by class name, the problem is there are 2 elements with the same names but one of them has something in addition:
<div class="ads-title ads-year">
۱۳۹۴ -
<span>بجنورد</span></div>
<div class="ads-title">پژو پارس ELX XUM</div>
The code I wrote to get ONLY 'ads-title' :
driver = webdriver.Chrome(r"./chromedriver")
driver.get('https://mashinbank.com/خرید-خودرو')
names = driver.find_elements_by_class_name('ads-title')
for name in names:
print(name.text)
But it gives me the content of both of them, my question is how to narrow it down to just 'ads-title' not included with 'ads-title ads-year' ? Thank you in advance.
CodePudding user response:
You can replace that to a css_selector
to locate only one matching node.
div[class='ads-title']
In code :-
names = driver.find_elements_by_css_selector("div[class='ads-title']")
for name in names:
print(name.text)
But I see with the above css selector
, there are 15 matching nodes.
In case you are looking for specific node which is
<div class="ads-title">پژو پارس ELX XUM</div>
then you can use this xpath
//div[@class='ads-title' and text()='پژو پارس ELX XUM']
In code :
driver.get('https://mashinbank.com/خرید-خودرو')
names = driver.find_elements_by_xpath("//div[@class='ads-title' and text()='پژو پارس ELX XUM']")
for name in names:
print(name.text)