Home > front end >  Python Selenium: How do I print the correct tag?
Python Selenium: How do I print the correct tag?

Time:01-14

I am trying to print by ID using Selenium. As far as I can tell, "a" is the tag and "title" is the attribute. See HTML below.

When I run the following code:

print(driver.find_elements(By.TAG_NAME, "a")[0].get_attribute('title'))

I get the output:

Zero Tolerance

So I'm getting the first attribute correctly. When I increment the code above:

print(driver.find_elements(By.TAG_NAME, "a")[1].get_attribute('title'))

My expected output is:

Aaliyah Love

However, I'm just getting blank. No errors. What am I doing incorrectly? Pls don't suggest using xpath or css, I'm trying to learn Selenium tags.

HTML:

<a  href="/en/channel/ztfilms" title="Zero Tolerance" rel="">Zero Tolerance</a>

...
<a  href="/[RETRACTED]/Aaliyah-Love/63565" title="Aaliyah Love" 

Screenshot of HTML

CodePudding user response:

Selenium locators are a toolbox and you're saying you only want to use a screwdriver (By.TAG_NAME) for all jobs. We aren't saying that you shouldn't use By.TAG_NAME, we're saying that you should use the right tool for the right job and sometimes (most times) By.TAG_NAME is not the right tool for the job. CSS selectors are WAY more powerful locators because they can search for not only tags but also classes, properties, etc.

It's hard to say for sure what's going on without access to the site/page. It could be that the entire page isn't loaded and you need to add a wait for the page to finish loading (maybe count links expected on the page?). It could be that your locator isn't specific enough and is catching other A tags that don't have a title attribute.

I would start by doing some debugging.

links = driver.find_elements(By.TAG_NAME, "a")
for link in links:
    print(link.get_attribute('title'))

What does this print?

  1. If it prints some blank lines sprinkled throughout the actual titles, your locator is probably not specific enough. Try a CSS selector

    links = driver.find_elements(By.CSS_SELECTOR, "a[title]")
    for link in links:
        print(link.get_attribute('title'))
    
  2. If instead it returns some titles and then nothing but blank lines, the page is probably not fully loaded. Try something like

    count = 20 # the number of expected links on the page
    link_locator = (By.TAG_NAME, "a")
    WebDriverWait(driver, 10).until(lambda wd: len(wd.find_elements(link_locator)) == count)
    links = driver.find_elements(link_locator)
    for link in links:
        print(link.get_attribute('title'))
    
  •  Tags:  
  • Related