我知道这是一个重复的问题,但是从网络上的所有答案中我都找不到解决方案,因为所有抛出错误。只需尝试从Web抓取标题并将其保存到txt文件即可。抓取代码效果很好,但是,它只保存了最后一个字符串,将所有标头绕过了最后一个。我试过循环,在抓取之前编写代码,追加到列表等,不同的抓取方法,但是都存在相同的问题。请帮助。
这是我的代码
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()))
'''
每次for
循环运行时,它都会覆盖headlines
变量,因此当您开始写入文件时,headlines
变量仅存储最后一个标题。一个简单的解决方案是将for
循环带入with
语句中,如下所示:
with open(filename, 'w') as file_object:
for headlines in page.find_all("h2"):
print(headlines.text.strip())
file_object.write(headlines.text.strip()+"\n") # write a newline after each headline