简体   繁体   中英

How to add multiple tags before a single tag BeautifulSoup

I have a single tag

I need to add three a tags before it having different text, I tried as:

 headTag = soup.find_all('h1', text='Attendance List') aTag = soup.new_tag('a') aTag['class'] = "btn btn-default pull-right" aTag.string = "Today" headTag[0].insert_before(aTag) aTag.string = "Weekly" headTag[0].insert_before(aTag) aTag.string = "Monthly" headTag[0].insert_before(aTag) 

But its only adding the last one, is there a better approach to do this without declaring multiple variables?

The problem is that you are only creating one tag, and then repeatedly modifying its string attribute, instead of creating three separate tags and inserting all of them. This is why it is only appending a single tag, and why the end result is the last of the strings.

To do what you want, use a for loop and create a new tag for each of the strings, like this:

headTag = soup.find_all('h1', text='Attendance List')

for s in ["Today", "Weekly", "Monthly"]:
    aTag = soup.new_tag('a') 
    aTag['class'] = "btn btn-default pull-right"
    aTag.string = s
    headTag[0].insert_before(aTag)

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