Python에서 BeautifulSoup을 사용하여 HTML 텍스트의 중첩 된 요소 내에서 텍스트 가져 오기

샘 스키너

매일 플레이하는 팀과 각 팀의 라인업에서 액티브 및 비 액티브 선수를 추출하려고합니다. 스크랩하려는 페이지의 URL은 https://stats.nba.com/lineups/ 입니다. 이 데이터를 얻기 위해 BeautifulSoup을 사용하고 있으며이를 얻기 위해 몇 가지 방법을 시도했지만 내에서 아무것도 추출 할 수없는 것 같습니다.

<div class=​"landing__flex-col lineups-game" data-game-state=​"3" nba-data-game=​"game" nba-with ng-include ng-repeat=​"game in games" src=​"'/​lineups-template.html'">​.

각 경기에서 각 팀을 얻고 싶습니다.

<div class=​"landing__flex-col lineups-game" data-game-state=​"3" nba-data-game=​"game" nba-with ng-include ng-repeat=​"game in games" src=​"'/​lineups-template.html'">​,

그리고 각 플레이어는

<div class=​"columns small-6 lineups-game__team lineups-game__team--htm" nba-with nba-with-data-team=​"game.h" ng-include src=​"'/​lineups-team-template.html'">​.

따라서 아래 html 코드 샘플에서 MEM, CHA, J. Valanciunas 및 J. Crowder에 대한 텍스트를 가져 와서 각 팀의 각 플레이어에 대해이 작업을 수행하려고합니다.

<div class="landing__flex-row lineups-games" ng-show="isLoaded &amp;&amp; hasData" aria-hidden="false">
          <!----><!----><div class="landing__flex-col lineups-game" ng-repeat="game in games" nba-with="" nba-data-game="game" data-game-state="3" ng-include="" src="'/lineups-template.html'">
  <div class="lineups-game__inner row">

    <div class="columns small-12 lineups-game__title">
      <a href="/game/0021900154/">
        <span class="lineups-game__team-name">MEM</span>
        <span class="lineups-game__vs">vs</span>
        <span class="lineups-game__team-name">CHA</span>
        <span class="lineups-game__status hide-for-live-game">Final</span>
        <span class="lineups-game__status hide-for-pre-game hide-for-post-game">Live</span>
      </a>
    </div>

    <!----><div class="columns small-6 lineups-game__team lineups-game__team--vtm" nba-with="" nba-with-data-team="game.v" ng-include="" src="'/lineups-team-template.html'">

  <!----><!----><div ng-if="team.hasBench" nba-with="" nba-with-data-team="team" ng-include="" src="'/lineups-confirmed-roster-template.html'">
  <div class="lineups-game__header">
    <img team-logo="" class="lineups-game__team-logo team-img" abbr="MEM" type="image/svg+xml" src="/media/img/teams/logos/MEM_logo.svg" alt="Memphis Grizzlies logo" title="Memphis Grizzlies logo">
    <span class="lineups-game__team-name">MEM</span>
  </div>

  <div class="lineups-game__roster-type lineups-game__roster-type--confirmed">Active List</div>

  <ul class="lineups-game__roster lineups-game__roster--official">
    <!----><li class="lineups-game__player lineups-game__player--starter" ng-repeat="pl in team.starters">
      <a href="/player/202685/">
        <span class="lineups-game__pos">C</span>
        <span class="lineups-game__name">J. Valanciunas</span>
      </a>
    </li><!----><li class="lineups-game__player lineups-game__player--starter" ng-repeat="pl in team.starters">
      <a href="/player/203109/">
        <span class="lineups-game__pos">SF</span>
        <span class="lineups-game__name">J. Crowder</span>
      </a>

나는 다른 방법 중에서도 다음을 시도하여 아무 소용이 없었습니다.

gamesSource = urllib.request.urlopen('https://stats.nba.com/lineups/').read()
gamesSoup = bs.BeautifulSoup(gamesSource,'html.parser')

teams = gamesSoup.find_all("span",{"class":"lineups-game__teams-name"})

반환되는 모든 것은 빈 목록이며 특정 'span'줄을 얻으려고 할 때 반환되는 모든 것은 'None'입니다.

무슨 일이 일어나고 있는지, 그리고 내가 얻고 자하는 정보에 접근하기 위해 무엇을 할 수 있는지 알려주세요.

감사.

HTML 코드 샘플

A. 패터슨

이 페이지는 api / js 호출을 통해 생성되므로 이미 언급 된 것을 피기 백하여 다른 스크래핑 라이브러리를 사용해야합니다. 나는 보통 셀레늄에 간다. 아래 코드는 모든 팀과 명단을 가져 와서 하나로 합칩니다. 이 코드에는 몇 가지 단점이있을 수 있지만 올바른 방향으로 진행될 것이라고 생각합니다.

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from datetime import date

desired_link = 'https://stats.nba.com/lineups/'

fire_opts = webdriver.FirefoxOptions()
fire_opts.add_argument("-headless")
fire_path = 'geckodriver.exe'
driver = webdriver.Firefox(options=fire_opts,executable_path=fire_path)
driver.get(desired_link)

team_names_list = driver.find_elements_by_class_name('lineups-game__team-name')
team_names = []
for name in team_names_list:
    team_names.append(name.text)

starting_lineup_list = driver.find_elements_by_class_name('lineups-game__roster--projected')
starting_lineup = []
for lineup in starting_lineup_list:
    starting_lineup.append(lineup.text)

driver.quit()

for teams, players in zip(team_names,starting_lineup):
    print(teams,players)

이렇게하면 페이지에있는 모든 다양한 팀이 다음과 같이 출력됩니다.

DET PG D. Rose
SG L. Kennard
SF T. Snell
PF B. Griffin
C A. Drummond

좀 더 형식이 더 좋을 수도 있지만 스프레드 시트 (또는 원하는대로)에 넣어 원하는대로 사용할 수 있습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관