使用beautifulsoup get_text() [英] Using beautifulsoup get_text()

查看:660
本文介绍了使用beautifulsoup get_text()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下代码块从网站解析我需要的字段:

I can parse the field that I need from a website with this code block:

response = requests.get(index_url)
soup = bs4.BeautifulSoup(response.text, "lxml")
poem = soup.select('div.siir p[id^=siir]')
print poem

但是它打印带有HTML标记.我正在尝试使用get_text()函数.当我尝试像这样使用时:

But it prints with HTML tags. I'm trying to use get_text() function. When I try to use like this:

print poem.get_text()

我收到此错误:

AttributeError: 'list' object has no attribute 'get_text'

我也试图这样使用:

poem = soup.select('div.siir p[id^=siir]').get_text()

我再次遇到相同的错误.解析正确的字段后如何消除HTML标签?

I get same error again. How can I eliminate the HTML tags after I parse the correct field?

推荐答案

soup.select()总是返回元素的 list ,而不仅仅是一个元素.依次在每个元素上调用get_text():

soup.select() always returns a list of elements, not just one element. Call get_text() on each element in turn:

for element in poem:
    print element.get_text()

如果只需要一个元素,则使用索引将其提取:

If you expected just one element, then extract it with indexing:

print poem[0].get_text()

这篇关于使用beautifulsoup get_text()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆