match string pattern in python
Question: I have a string that can contain links:

    
    
    <a href="http://site1.com/">Hello</a> <a href="http://site2.com/">Hello2</a>
    <a href="http://site3.com">Hello3</a> ...
    

How can I extract the text (not the link) of all html tags "Hello", "Hello2",
"Hello3" ... ? I'm thinking of a list that should contain all texts.


Answer: Using [lxml](http://codespeak.net/lxml/):

    
    
    import lxml.html as LH
    
    content = '''
    <a href="http://site1.com/">Hello</a> <a href="http://site2.com/">Hello2</a>
    <a href="http://site3.com">Hello3</a>
    <a href="/">go <b>home</b>, dude!</a>
    '''
    
    doc = LH.fromstring(content)
    texts = [elt.text_content() for elt in doc.xpath('//a')]
    print(texts)
    

yields

    
    
    ['Hello', 'Hello2', 'Hello3', 'go home, dude!']
    

