You never call
Then can split on
text
,if you do text inside pre tag will get a \n
for each line.Then can split on
\n
and take out line you want.from bs4 import BeautifulSoup html = '''\ <html> <body> <pre> Text in a pre element is displayed in a fixed-width XYZ57 ABCD 141800 font, and it preserves both spaces and line breaks </pre> </body> </html>''' soup = BeautifulSoup(html,'lxml') y = soup.find('pre') # Call text text = y.text my_line = '' for line in text.split('\n'): if line.startswith('XYZ'): my_line += line print(my_line)
Output:XYZ57 ABCD 141800