从Resultset中删除换行符(Python)

时间:2016-09-10 16:06:05

标签: python beautifulsoup

我的ResultSet包含以下信息 -

[<div id="Description">\n    This is the content example.\n\r\nThese characters I need to remove from complete string.\n\r\nI tried strip,lstrip,rstrip and replace.\n\r\nBut for these I found the Attributeerror: resultset object has no attribute 'strip'(lstrip/rstrip/replace).\n</div>]

我用:

检索了它
webPage=urllib2.urlopen(GivenUrl)
soup=BeautifulSoup(webPage,"html.parser")
soupResultSet=soup.findAll('div',id='Description') #This result set contains the above information.

我正在使用python 2.7.12。

原始HTML:

<div id="Description">
    This is the content example.
These characters I need to remove from complete string.
I tried strip,lstrip,rstrip and replace.
But for these I found the Attributeerror: resultset object has no attribute 'strip'(lstrip/rstrip/replace).
</div>

1 个答案:

答案 0 :(得分:1)

ResultSet是一个简单的list子类。列表上不存在str.strip()div元素也不存在。

从每个元素中获取文本,您可以使用支持直接剥离的Tag.get_text() method

[tag.get_text(strip=True) for tag in soup.find_all('div', id='Description')]

由于您似乎在寻找具有<div>属性的id,因此应该只有一个这样的元素。在这种情况下,您应该使用soup.find_all()而不是使用soup.find(),而只是获取一个元素而不是列表:

soup.find('div', id='Description').get_text(strip=True)

这为您提供了一个 str对象,从开头和结尾删除了空格。如果您还需要从字符串中间删除所有换行符,则可以进一步处理此问题。