Home > Net >  selenium python : loop throtgh anchor elements in div and get links
selenium python : loop throtgh anchor elements in div and get links

Time:07-14

hi im trying to loop throtgh anchor elements in div and get links of this div element

<div >
    <a  href="link">text 1</a>
    <a  href="link">text 2</a>
    <a  href="link">text 3</a>
    <a  href="link">text 4</a>
</div>

i tried looping by CSS_SELECTOR but it not working for all pages because the link in herf changes

lists = driver.find_elements(By.CSS_SELECTOR,'a[href*="dzdzdzd"]')
    s_links = []
    for i in lists :
        s_links.append(i.get_attribute('href'))

CodePudding user response:

Use below locator type

Or you can use xpath as "//a"

lists = driver.find_elements(By.TAGNAME,'a')
    s_links = []
    for i in lists :
        s_links.append(i.get_attribute('href'))

CodePudding user response:

I solved the problem with this code

def seasons():
    lists = driver.find_element(By.CLASS_NAME,'List').find_elements(By.TAG_NAME,'a')
    s_links = []
    for i in lists :
        
        s_links.append(i.get_attribute('href'))
        
        with open('s_links.txt', 'a') as f :
                f.write(i.get_attribute('href'))
                f.write("\n")
    return s_links

  • Related