【问题标题】:Beautiful Soup python .get full information from htmlBeautiful Soup python .get full information from html
【发布时间】:2018-07-03 12:08:10
【问题描述】:

我正在尝试通过 BeautifulSoup 获取我在 Telegram 上的帖子的浏览量。例如,我想从我的频道帖子编号 956 中获取它:https://t.me/dayygesstt/956

<span class="tgme_widget_message_views">3.1K</span>

所以“3.1K”是我需要的。

import requests
from bs4 import BeautifulSoup

def get_html(url):
    r = requests.get(url,'lxml')
    return r.text
url='https://t.me/dayygesstt/956'
html=get_html(url)
soup=BeautifulSoup(html, )

x = soup.findAll("div", {"class": "tgme_page tgme_page_post"})

for i in x :
    r=i.findAll("div", {"class": "tgme_page_widget"})
    print(r)

然后打印出来:

[<div class="tgme_page_widget" id="widget">
<script async="" data-telegram-post="dayygesstt/956" data-width="100%" src="https://telegram.org/js/telegram-
widget.js?4"></script>
</div>]

我尝试了不同的方法,但无法获得更多信息。请帮助我,我做错了什么?如何正确获取信息?

【问题讨论】:

  • 它不起作用,因为该 div 元素的内容是使用 javascript 动态加载的。
  • 谢谢,我该怎么办?

标签: python python-3.x parsing beautifulsoup telegram


【解决方案1】:

您可以使用在脚本中加载 iframe 的 URL。然后你只得到没有杂物的小部件。为此,获取原始 URL 并附加一个查询字符串“embed=1”。

import requests
from bs4 import BeautifulSoup

url = 'https://t.me/dayygesstt/956?embed=1'
r = requests.get(url)
soup = BeautifulSoup(r.text, "html.parser")
views = soup.find("span", {"class": "tgme_widget_message_views"})
print(views.text)

【讨论】:

    【解决方案2】:

    我认为您需要定义与 BeautifulSoup 一起使用的解析器,以便它正确解析 HTML,所以这一行;

    soup=BeautifulSoup(html, )
    

    需要这样;

    soup=BeautifulSoup(html, 'html.parser')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-27
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多