在BeautifulSoup / Python中,如何从结果集中提取单个元素?

时间:2019-11-04 15:50:14

标签: python-3.x beautifulsoup resultset

我正在使用Python 3.7和BeautifulSoup4。我在从元素获取文本时遇到问题。我正在尝试

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

但是在“ author_elt = author_elts.first”这一行,我遇到了错误

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()

从ResultSet中提取元素的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

find_all返回一个列表,为什么不使用author_elts[0]来获取第一个元素?