Here is my Problems and Codes
Problems.
- Almost second wrapper has a button (some second wrapper has a link instead of a button)
- To avoid second wrapper that contains only link or missing button, I made condition(var:button_check) and if statement.
- but, these codes works generally but, it always stucks at the wrapper that has link, then throw Message: Unable to locate element: div[role="button"]
def clicking_see_more(self) -> None:
wrappers = self.find_elements_by_css_selector('div[style="text-align: start;"]')
def button_click():
for i, wrapper in enumerate(wrappers):
if i % 2 == 1:
button_check = bool(wrapper.find_element_by_css_selector('div[role="button"]'))
if not button_check:
continue
else:
btn = wrapper.find_element_by_css_selector('div[role="button"]')
btn.click()
time.sleep(0.5)
try:
button_click()
except NoSuchElementException as e:
print(e)
CodePudding user response:
You should use find_elements_by_css_selector
instead of find_element_by_css_selector
, since elements
will return a list, you can check for it's size if it is >0
then element must be present. If not, then element is not present.
try this :
def button_click():
for i, wrapper in enumerate(wrappers):
button_check = len (driver.find_elements_by_css_selector('div[role="button"]'))
if button_check == 0:
continue
else:
btn = driver.find_element_by_css_selector('div[role="button"]')
btn.click()
time.sleep(0.5)