Search code examples
python-3.xbeautifulsoupresultset

In BeautifulSoup / Python, how do I extract a single element from a result set?


I'm using Python 3.7 and BeautifulSoup 4. I'm having a problem getting text from an element. I'm trying this

req = urllib2.Request(fullurl, headers=settings.HDR)
html = urllib2.urlopen(req, timeout=settings.SOCKET_TIMEOUT_IN_SECONDS).read()
bs = BeautifulSoup(html, features="lxml")
...
author_elts = bs.find_all("a", class_="author")
author_elt = author_elts.first

But on the "author_elt = author_elts.first" line, I'm getting the error

AttributeError: ResultSet object has no attribute 'first'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()

What's the right way to extract the element from the ResultSet?


Solution

  • find_all return a list, why did you not use author_elts[0] to get the first element ?