I know that this is a repeated question however from all answers on web I could not find the solution as all throwing error. Simply trying to scrape headers from the web and save them to a txt file. scraping code works well, however, it saves only last string bypassing all headers to the last one. I have tried looping, putting writing code before scraping, appending to list etc, different method of scraping however all having the same issue. please help.
here is my code
def nytscrap():
from bs4 import BeautifulSoup
import requests
url = "http://www.nytimes.com"
page = BeautifulSoup(requests.get(url).text, "lxml")
for headlines in page.find_all("h2"):
print(headlines.text.strip())
filename = "NYTHeads.txt"
with open(filename, 'w') as file_object:
file_object.write(str(headlines.text.strip()))
'''