TypeError: expected string or buffer while using regular expression in python
Question: I wrote this code to remove the tags that match like this

`<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>`

**CODE:**

    
    
    import mechanize
    import urllib2
    from bs4 import BeautifulSoup
    import re
    med = 'paracetamol'
    listiterator = []
    listiterator[:] = range(2,16)
    br = mechanize.Browser()
    br.set_handle_robots(False)
    r=br.open("http://www.drugs.com/search-wildcard-phonetic.html")
    br.select_form(nr=0)
    br.form['searchterm'] = med
    br.submit()
    url = br.response().geturl()
    print url
    mainurl = urllib2.urlopen(url).read()
    subpages = re.findall("<a href=\"(.*?).html\">[^>]*>", mainurl)
    for sub in subpages:
        if sub.startswith("http:"):
            soup = BeautifulSoup(urllib2.urlopen(sub).read())
            m = soup.find_all("div", {"class":"contentBox"})
            head = m[0].find_all(["h2","p"])
            for i in head:
                m = re.match("<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>").group()
                if not m:
                    print i         
            break
    

I got this error:

    
    
    m = re.match("<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>",i).group()
      File "/usr/lib/python2.7/re.py", line 137, in match
        return _compile(pattern, flags).match(string)
    TypeError: expected string or buffer
    


Answer: You get that error because the type of the variable `i` is `<class
'bs4.element.Tag'>`, and `match` needs a buffer or string. Secondly, if the
pattern doesn't match, then the `.match` call will return `None`, so your
`.group` will be a null pointer exception.

Here's a _quick and dirty_ "solution" I don't recommend:

    
    
    m = re.match("<p><b>See also:</b> <a href=\"(.*?)\">(.*)</a>(.*)</p>", str(i))
    if not m:
        print i
    

A better solution would be to rewrite without trying to parse HTML yourself,
letting BeautifulSoup do its job. For example, instead of your regex pattern,
exclude the items that contain the text `See also` and an anchor tag:

    
    
    if i.find(text='See also:') and i.find('a'):
        continue
    print i
    

