[英]How to fix AttributeError: ResultSet object has no attribute 'get_text'
I'm trying to get the top repositories of 3d topic from github based on the stars.我正在尝试根据星星从 github 获取 3d 主题的顶级存储库。
topic_page_url = 'http://github.com/topics/3d'
response = requests.get(topic_page_url)
topic_doc = BeautifulSoup(response.text,'html.parser')
star_tags = topic_doc.find_all('span',{'class':'Counter js-social-count'})
#print(star_tags[0].text) has given result 11.k
def parse_star_count (stars_str):
stars_str = stars_str.strip()
if stars_str[-1] == 'k':
return int(float(stars_str[:-1]) * 1000)
return int(stars_str)
#it's working if it's only one element
parse_star_count(star_tags[0].get_text().strip( ))
#if i try to print all it is showing the error
parse_star_count(star_tags.get_text().strip( ))
This is the error这是错误
AttributeError: ResultSet object has no attribute 'text'. AttributeError:ResultSet 对象没有属性“文本”。 You're probably treating a list of items like a single item.您可能将项目列表视为单个项目。 Did you call find_all() when you meant to call find()?当您打算调用 find() 时,您是否调用了 find_all()?
You might want to loop through the results, using a for
loop:您可能希望使用for
循环遍历结果:
topic_page_url = 'http://github.com/topics/3d'
response = requests.get(topic_page_url)
topic_doc = BeautifulSoup(response.text,'html.parser')
star_tags = topic_doc.find_all('span',{'class':'Counter js-social-count'})
#print(star_tags[0].text) has given result 11.k
def parse_star_count (stars_str):
stars_str = stars_str.strip()
if stars_str[-1] == 'k':
return int(float(stars_str[:-1]) * 1000)
return int(stars_str)
for star_tag in star_tags:
parse_star_count(star_tag.get_text().strip( ))
BeautifulSoup find_all() method returns resultset object. BeautifulSoup find_all() 方法返回结果集对象。 You can verify that by using type() function:您可以使用 type() 函数来验证这一点:
type(star_tags)
bs4.element.ResultSet
To get the text from each element, try to loop through each element and then call get_text() method on it.要从每个元素中获取文本,请尝试遍历每个元素,然后对其调用 get_text() 方法。
for star in star_tags:
print(star.get_text())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.