Link to home
Start Free TrialLog in
Avatar of Richard Comito
Richard ComitoFlag for United States of America

asked on

Printing the next 10 lines after a word is found with BeautifulSoup4

I am doing a loop using Python3 and BeautifulSoup4 and I want to be able to print out the next 10 lines after I found a word in the output.  I am using find_all to pull our all the text in the TR tag.  I mainly want the text in the TD tag, but what I have seems to be giving me what I want.  If I can improve, suggestion are always welcomed

But my first issue is just getting it to print when I found the word I am looking for.  If I remove the IF statement, then I can see I am getting all the text I want.

Here is what I have so far.

from bs4 import BeautifulSoup
import requests

 
url = 'http://www.somewebsite.com'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')


for table in soup.find_all('tr'):
    if table.text == 'Actuals':
        print(table.text)

Open in new window




Thank you
ASKER CERTIFIED SOLUTION
Avatar of Flabio Gates
Flabio Gates

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Flabio Gates
Flabio Gates

Question inactive