python - 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>
如何获得部分“视图”和“交互”?
解决方案
您需要从评论中提取 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
...
推荐阅读
- php - WooCommerce wc_update_product_stock 将数字作为十进制存储在数据库中
- php - 尝试登录旧代码时 PDO 不起作用
- android - 通过 Selenium Android 驱动程序运行测试用例时出现 java.lang.NullPointerException
- powershell - 如何在 PowerShell 中将输出写入带有参数路径的文件?
- winapi - 如何在mfc vc++中透明编辑框的背景?
- css - 显示 div 隐藏 CSS 的悬停按钮
- symfony - 在集合 FormType 的每一行上插入父 Id
- xamarin.forms - PWA(Progressive Web App) - 从 Windows UWP 应用程序启动 PWA
- c# - 从长字符串 Regex 中获取匹配的子字符串
- entity-framework - 在 NetCore 中使用带有 SQLite 的“where”总是返回空列表