【问题标题】:Can't get data from inside of span-tag with beautifulsoup无法使用 beautifulsoup 从 span-tag 内部获取数据
【发布时间】:2019-06-26 20:13:17
【问题描述】:

我正在尝试抓取 Instagram 页面,并希望获取/访问跨度标签内的 div-标签。但我不能! Instagram 页面的 HTML 如下所示

 <head>--</head>
    <body>
       <span id="react-root" aria-hidden="false">
       <form enctype="multipart/form-data" method="POST" role="presentation">…</form>
       <section class="_9eogI E3X2T">
          <main class="SCxLW  o64aR" role="main">
             <div class="v9tJq VfzDr">
                 <header class=" HVbuG">…</header>
                 <div class="_4bSq7">…</div>
                 <div class="fx7hk">…</div>
             </div>
          </main>
      </section>
    </body>

我是这样的

from bs4 import BeautifulSoup
import urllib.request as urllib2
html_page = urllib2.urlopen("https://www.instagram.com/cherrified_/?hl=en")
soup = BeautifulSoup(html_page,"lxml")
span_tag = soup.find('span') # return span-tag correctly
span_tag.find_all('div')    # return empty list, why ?

请同时举一个例子。

【问题讨论】:

  • 请提供一个小例子,其他人可以运行并重现您的错误。
  • 完成,先生,现在你可以检查了

标签: python beautifulsoup


【解决方案1】:

Instagram 是一个由 React 提供支持的单页应用程序,这意味着它的源只是一个简单的“空”页面,它加载 JavaScript 以在下载后在浏览器中动态生成内容。

点击“查看源代码”或在 Chrome 中转到 view-source:https://www.instagram.com/cherrified_/?hl=en。这是您使用 urllib.request 下载的 HTML。

您可以看到有一个&lt;span&gt; 标记,其中不包含&lt;div&gt; 标记。 (注意:&lt;div&gt; 在 &lt;span&gt; is not allowed 中)。

无法以这种方式抓取 instagram.com。 It also might not be legal(我不是律师)。

注意事项:

  • 您的 HTML 代码示例不包含 &lt;span&gt; 的结束标记。
  • 您的 HTML 代码示例与您在 python sn-p 中提供的链接不匹配。
  • 在 python sn-p 的最后一行中,您可能指的是 span_tag.find_all('div')(注意变量名和单数 'div')。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2020-05-19
    • 2012-10-10
    • 1970-01-01
    相关资源
    最近更新 更多