【发布时间】:2020-08-08 02:47:32
【问题描述】:
我尝试从 VK 组获取文章。但我找不到从 VK API 获取它们的任何可能性。也许有人面临同样的问题?有没有机会使用 get for Posts 来获取文章? (我正在使用 vk_api python 包)
【问题讨论】:
标签: python integration social-media vk
我尝试从 VK 组获取文章。但我找不到从 VK API 获取它们的任何可能性。也许有人面临同样的问题?有没有机会使用 get for Posts 来获取文章? (我正在使用 vk_api python 包)
【问题讨论】:
标签: python integration social-media vk
免责声明:我基本上无法完全理解 VK API 文档中的俄语文档。
似乎没有记录在 VK API 中检索文章的方法,但如果您已经在使用 Python 和 vk_api 那么您可以使用在主类中实例化的会话。这不会给你一篇文章,而是 HTML 本身,所以如果你需要,你必须解析它来提取文本。像这样的东西是我在我的代码中使用的:
import vk_api
vk_session = vk_api.VkApi(login, password)
try:
vk_session.auth(token_only=True)
except vk_api.AuthError as error_msg:
print(error_msg)
return
# Note that calls are going to be performed with the vk_session object, not the API class.
article_url = "https://vk.com/@riakatyusha-akademik-fortov-buduschee-budet-takim-kakim-my-ego-opredelim"
article_content = vk_session.http.get(article_url).text
这应该可以帮助您入门。从这里您只需要处理 HTML 代码。不幸的是,the VK methods page 中没有关于文章的文档,所以对于处理文章,我们可能无能为力。
这里有一些代码可以帮助您开始从用户或社区页面中提取所有文章。这里唯一的依赖是 bs4。我使用了 lxml 解析器,因为它是最快的,我的机器上有它,但如果你不想要/拥有它,你可能会使用其他的,如 BeautifulSoup's docs
中所建议的那样这个非常简单的方法应该可以帮助您检索最近发布在组中的 20 篇文章。我找不到加载更多项目的方法,但看起来你需要使用 author_page.php。不过,这看起来很困难。可能你会在audio class of VK_api 中找到一些灵感或在their github. 中提问
假设您不想访问私人组,这里是代码(我认为使用 VK_api 请求会话调用 post 和 get 方法就足以登录 vk,但似乎您需要额外的步骤):
import requests
from bs4 import BeautifulSoup
group_url = "https://m.vk.com/@riakatyusha"
body = requests.get(group_url)
soup = BeautifulSoup(body.text, "lxml")
articles_list = soup.find_all("div", class_="author-page-article")
for article in articles_list:
# VK includes relative URLS in articles so you'd need to complete it first.
url = article.a["href"]
url = "https://m.vk.com"+url
# Optionally, we could remove the GET params you have in urls such as context&ref.
url = url.split("?")[0]
# We still might retrieve some extra info in case you'd need.
title = article.find("span", class_="author-page-article__title").text
summary = article.p.text
print(title, summary, url)
【讨论】: