我刚刚写了一个简单的 python 程序来从谷歌新闻中提取链接,这是成功的。我现在遇到的问题是我想将所有这些链接写入或附加到文本文件中,但它只写入第一个链接而不是所有链接。我如何实现这一点?
我的代码如下所示
from urllib.request import urlopen
from bs4 import BeautifulSoup as Soup
class Scraper:
def __init__(self, site):
self.site = site
def scrape(self):
req = urlopen(self.site)
html = req.read()
parser = "html.parser"
sp = Soup(html, parser)
news_list = sp.find_all("a")
for tag in news_list:
url = tag.get("href")
print("\n", url)
print("-" * 110)
with open("elder.txt", "w+") as f:
f.write(str(url))
news = "https://news.google.com"
Scraper(news).scrape()