【发布时间】:2019-01-02 10:10:01
【问题描述】:
我一直在尝试从 pantip.com 提取数据,包括标题、帖子和所有使用 beautifulsoup 的 cmets。 但是,我只能提取标题和帖子。我无法获得 cmets。 这是标题和帖子的代码
import requests
import re
from bs4 import BeautifulSoup
# specify the url
url = 'https://pantip.com/topic/38372443'
# Split Topic number
topic_number = re.split('https://pantip.com/topic/', url)
topic_number = topic_number[1]
page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')
# Capture title
elementTag_title = soup.find(id = 'topic-'+ topic_number)
title = str(elementTag_title.find_all(class_ = 'display-post-title')[0].string)
# Capture post story
resultSet_post = elementTag_title.find_all(class_ = 'display-post-story')[0]
post = resultSet_post.contents[1].text.strip()
我试图通过 id 查找
elementTag_comment = soup.find(id = "comments-jsrender")
我得到了下面的结果。
elementTag_comment =
<div id="comments-jsrender">
<div class="loadmore-bar loadmore-bar-paging"> <a href="javascript:void(0)">
<span class="icon-expand-left"><small>▼</small></span> <span class="focus-
txt"><span class="loading-txt">กำลังโหลดข้อมูล...</span></span> <span
class="icon-expand-right"><small>▼</small></span> </a> </div>
</div>
问题是我怎样才能得到所有的 cmets。请建议我如何解决它。
【问题讨论】:
-
乍一看,帖子似乎存在延迟加载。 (评论在页面后异步加载)。如果您查看网络选项卡,您可以看到“render_cmets”资源网络调用...请参考这个答案:stackoverflow.com/a/47851306/6283258
-
soup.find()只会返回找到的第一个元素。如果你想要所有 id = "cmets-jsrender" 的标签,你需要使用soup.find_all()。然后根据您想要做什么,可能需要遍历每个元素。
标签: python selenium web-scraping beautifulsoup nlp