0

I have a piece of html code that look like this:

<div class="menu-item"> 
      <a class="menu-link" href="/dashboard/apple"> C-apple</a>
</div>
<div class="menu-item"> 
      <a class="menu-link" href="/dashboard/bench"> C-bench</a>
</div>

but i wanna read the href="/dashboard/{name}"> {title} </a> from a python list and display it using a for loop or while loop instead of hard coding, how can i do that? thanks

1
  • Try loading it with beautifulsoup Commented Oct 27, 2015 at 23:19

2 Answers 2

1

You can look up the HTMLParser

Here is an Example

from HTMLParser import HTMLParser

# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    a = 0
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.a = 1
            print 'name:', dict(attrs)['href'].split('/')[-1]
    def handle_data(self, data):
        if self.a == 1:
            print 'title:', data
    def handle_endtag(self, tag):
        self.a = 0

# instantiate the parser and fed it some HTML
parser = MyHTMLParser()
parser.feed('''
<div class="menu-item"> 
      <a class="menu-link" href="/dashboard/apple"> C-apple</a>
</div>
<div class="menu-item"> 
      <a class="menu-link" href="/dashboard/bench"> C-bench</a>
</div>
''')

And you run it you will get the output

name: apple
title:  C-apple
name: bench
title:  C-bench
Sign up to request clarification or add additional context in comments.

2 Comments

i am actually looking to feed those variables as a tuple to html from a python file, i was actually looking some thing like <div class="menu-item"> {% for name, project in dashboard_data %} <ul> <li><a href="/dashboard/" + {project}>{name}</a></li> </ul> {% endfor %} </div>
0

thanks guys for the help and this solved my problem

{%for name, title in tuples:%}
   <div class="menu-item">
      <a class="menu-link" href="/dashboard/{{title}}">{{name}}</a>
   </div>
{%endfor%}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.