fightstarr20
fightstarr20

Reputation: 12608

Python Selenium save list items as array

I am using Python Selenium to look through some HTML and find elements. I have the following HTML saved into Python...

<section id="categories">
    <ul id="category_list">
        <li id="category84">
            <a href="www.example.com/samplelink">Sample Category</a>
        </li>
        <li id="category984">
            <a href="www.example.com/samplelink44">Another Category</a>
        </li>
        <li id="category22">
            <a href="www.example.com/samplelink">My Sample Category</a>
        </li>
    </ul>
</section>

I can find the categories section easy enough but now I would like to loop through each list item and save it's name and href link into an array.

Anyone got a similar example I can see?

Upvotes: 1

Views: 2590

Answers (1)

alecxe
alecxe

Reputation: 474031

Sure, let's use a CSS selector locator and a list comprehension calling .get_attribute("href") to get the link and .text to get the link text:

categories = driver.find_elements_by_css_selector("#categories #category_list li[id^=category] a")

result = [{"link": category.get_attribute("href"), "text": category.text} 
          for category in categories]
print(result)

Upvotes: 3

Related Questions