简体   繁体   中英

How to find all element and text by using Selenium in python

There is a Anchor tag( <a> ) under the div class and under the <a> tag there is a <p> tag with the class and the <p> class matched with 12 item. I was trying to find all the text under the p tag using python. Here is my code.
First approach:

for ele in  driver.find_element_by_xpath('//p[@class="BrandCard___StyledP-sc-1kq2v0k-1 bAWFRI text-sm font-semibold text-center cursor-pointer"]'):
   print(ele.text)

Second approach:

content_blocks=driver.find(By.CSS_SELECTOR, "div.CategoryBrand__GridCategory-sc-17tjxen-0.PYjFK.my-4")
for block in content_blocks:
    elements = block.find_elements_by_tag_name("a")
    for el in elements:
        list_of_hrefs.append(el.text)

but every time it gives me an error "WebElement is not iterable".
I have added a picture of the page element.
Page Element click here

This should help you, on your first approach you miss the S of elements (with S will return a list with all matches, without the first match). I use xpath with contains some substring in the class.

r_elems = driver.find_elements_by_xpath("//p[contains(@class, 'BrandCard')]")
[x.text for x in r_elems]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM