首页 > 解决方案 > BeautifulSoup 从评论 html 中提取文本

问题描述

抱歉,如果这个问题对其他人来说很相似,我无法使任何其他解决方案起作用。我正在使用beautifulsoup 抓取一个网站,并试图从一个已评论的表字段中获取信息:

<td>
    <span class="release" data-release="1518739200"></span>
    <!--<p class="statistics">

                      <span class="views" clicks="1564058">1.56M Clicks</span>

                        <span class="interaction" likes="0"></span>

    </p>-->
</td>

如何获得部分“视图”和“交互”?

标签: pythonweb-scrapingbeautifulsoupcomments

解决方案


您需要从评论中提取 HTML 并使用 BeautifulSoup 再次解析它,如下所示:

from bs4 import BeautifulSoup, Comment
html = """<td>
    <span class="release" data-release="1518739200"></span>
    <!--<p class="statistics">

                      <span class="views" clicks="1564058">1.56M Clicks</span>

                        <span class="interaction" likes="0"></span>

    </p>-->
</td>"""
soup = BeautifulSoup(html , 'lxml')
comment = soup.find(text=lambda text:isinstance(text, Comment))
commentsoup = BeautifulSoup(comment , 'lxml')
views = commentsoup.find('span', {'class': 'views'})
interaction= commentsoup.find('span', {'class': 'interaction'})
print (views.get_text(), interaction['likes'])

输出:

156 万点击 0

如果评论不是页面上的第一个评论,您需要像这样对其进行索引:

comment = soup.find_all(text=lambda text:isinstance(text, Comment))[1]

或从父元素中找到它。

更新以回应评论:

您可以为此使用父 'tr' 元素。您提供的页面有“共享”而不是“交互”,所以我希望您有一个 NoneType 对象,它给了您看到的错误。如果需要,您可以在代码中为 NoneType 对象添加测试。

from bs4 import BeautifulSoup, Comment
import requests
url = "https://imvdb.com/calendar/2018?page=1"
html = requests.get(url).text
soup = BeautifulSoup(html , 'lxml')

for tr in soup.find_all('tr'):
    comment = tr.find(text=lambda text:isinstance(text, Comment))
    commentsoup = BeautifulSoup(comment , 'lxml')
    views = commentsoup.find('span', {'class': 'views'})
    shares= commentsoup.find('span', {'class': 'shares'})
    print (views.get_text(), shares['data-shares'])

输出:

3.60K Views 0
1.56M Views 0
220.28K Views 0
6.09M Views 0
133.04K Views 0
163.62M Views 0
30.44K Views 0
2.95M Views 0
2.10M Views 0
83.21K Views 0
5.27K Views 0
...

推荐阅读