如何在python中刮取标签文本?

2024-10-16 20:43:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从网站上刮掉球员名单,但名字都在标签上。我不知道如何刮标签上的文字。 这里是链接 https://athletics.baruch.cuny.edu/sports/mens-swimming-and-diving/roster 例如,从html我们有 如何从标签中刮取文本

<div class="sidearm-roster-player-image column">                                                                    
  <a data-bind="click: function() { return true; }, clickBubble: false" href="/sports/mens-swimming-and-diving/roster/gregory-becker/3555" aria-label="Gregory Becker - View Full Bio" title="View Full Bio">
    <img class="lazyload" data-src="/images/2018/10/19/GREGORY_BECKER.jpg?width=80" alt="GREGORY BECKER">
  </a>                                                              
</div>

Tags: anddivviewdata标签fullclassbio
2条回答

下面是帮助您从a标记中提取名称的代码

from bs4 import BeautifulSoup

with open("<path-to-html-file>") as fp:
    soup = BeautifulSoup(fp, 'html.parser') #parse the html
    
tags = soup.find_all('a') # get all the a tag
for tag in tags:
    print(tag.get('aria-label')) #get the required text

您可以在BeautifulSoup中使用.get()方法。首先使用任何选择器或find/find_all选择elem中的元素或任何其他变量。然后尝试:

print(elem.get('aria-label'))

相关问题 更多 >