How to store a set of multiple p tag texts to a single variable in space delimit with BeautifulSoup in Python

Viewed 66

How can I store texts from multiple HTML p tags in a single variable with space delimit with BeautifulSoup in the following example? I'm brand new to Python. Thank you!

from bs4 import BeautifulSoup

HTML = '''
</tr>
<td class="up">
<p class="pie_chart_val">+1.30%</p>
</td>
<td class="down">
<p class="pie_chart_val">-1.33%</p>
</td>
<td class="up">
<p class="pie_chart_val">+1.58%</p>
</td>
<td class="up">
<p class="pie_chart_val">+1.61%</p>
</td>
</tr>
'''

soup = BeautifulSoup(HTML, 'lxml')
values = soup.find_all('p', class_="pie_chart_val")
for value in values:
    value = value.text
    print(value)
2 Answers

In print statement itself you can put end="," as parameter to make answer in one line

from bs4 import BeautifulSoup

html=  """<tr>
<td class="up">
<p class="pie_chart_val">+1.30%</p>
</td>
<td class="down">
<p class="pie_chart_val">-1.33%</p>
</td>
<td class="up">
<p class="pie_chart_val">+1.58%</p>
</td>
<td class="up">
<p class="pie_chart_val">+1.61%</p>
</td>
</tr>
"""

soup = BeautifulSoup(html, 'lxml')
values = soup.find_all('p', class_="pie_chart_val")
for value in values:
    print(value.text,end=",")

Output:

+1.30%,-1.33%,+1.58%,+1.61%,

OR :

you can try to append data to list and print in one line

lst=[i.get_text(strip=True) for i in values]
print(*lst,sep=",")

Output:

+1.30%,-1.33%,+1.58%,+1.61%

To get in single variable

x=",".join(lst)
print(x)

Output:

+1.30%,-1.33%,+1.58%,+1.61%

You can do like this using string concatenation.

from bs4 import BeautifulSoup

HTML = '''
</tr>
<td class="up">
<p class="pie_chart_val">+1.30%</p>
</td>
<td class="down">
<p class="pie_chart_val">-1.33%</p>
</td>
<td class="up">
<p class="pie_chart_val">+1.58%</p>
</td>
<td class="up">
<p class="pie_chart_val">+1.61%</p>
</td>
</tr>
'''

soup = BeautifulSoup(HTML, 'lxml')
values = soup.find_all('p', class_="pie_chart_val")
ans = ''
for value in values:
    ans += value.text.strip() + ' '

print(ans)

ans is a string that has space separated texts of <p> tags.

+1.30% -1.33% +1.58% +1.61%
Related