【发布时间】:2021-02-15 17:22:27
【问题描述】:
我有一个简单的抓取功能,可以从给定的 url 返回特定的东西。 它发回我想以某种方式将内容保存到 .md 文件的字典。 代码如下:
import requests
from bs4 import BeautifulSoup
def get_data(url):
page = requests.get(url).text
soup = BeautifulSoup(page, 'html.parser')
iframe = []
yt_secondary = []
div = soup.find_all('div', attrs={'class': 'tags'})
for entry in div:
tags = entry.text.strip().replace('#', '').split('\n')
songs_links = soup.find_all('iframe')[0]
iframe.append(songs_links)
entry = {'tags': tags,
'iframe': songs_links}
return entry
if __name__ == "__main__":
print(get_data('https://nikisaku.tumblr.com/post/643205680992485376/test'))
它会按预期返回:
{'tags': ['Tagged: testing, test2, test3, .'], 'iframe': <iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/bwKfVwiUpvo?feature=oembed&enablejsapi=1&origin=https://safe.txmblr.com&wmode=opaque" width="500"></iframe>}
现在我希望能够以以下格式将其保存到 .md 文件中:
---
tags: Tagged: testing, test2, test3, .
---
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="281" id="youtube_iframe" src="https://www.youtube.com/embed/bwKfVwiUpvo?feature=oembed&enablejsapi=1&origin=https://safe.txmblr.com&wmode=opaque" width="500"></iframe>
这甚至可以这样保存吗? 我需要将它作为这个功能,因为我将使用它来浏览 X 个给定页面以抓取标签和链接(有效),并且对于每个结果我都必须创建一个新的 .md 文件。
提前致谢!
【问题讨论】:
标签: python file dictionary save