2016-11-02 4 views
2
import requests 
from bs4 import BeautifulSoup 

request = requests.get("http://www.lolesports.com/en_US/worlds/world_championship_2016/standings/default") 
content = request.content 
soup = BeautifulSoup(content, "html.parser") 
team_name = soup.findAll('text', {'class': 'team-name'}) 

print(team_name) 

私はURLからデータを解析しようとしています: "http://www.lolesports.com/en_US/worlds/world_championship_2016/standings/default" <text class="team-name">SK Telecom T1</text>の下には個々のチーム名があります。私がしようとしているのは、そのデータ(SK Telecom T1)を解析して画面に表示することですが、代わりに空のリストを取得します。私は間違って何をしていますか?BeautifulSoup4でデータを解析する

答えて

2

は、すべての動的コンテンツはhttp://api.lolesports.com/api/v1/leaguesに、単純なGETリクエストでJSON形式で取得することができます:あなたが何をしたいあなたのデータの全体の多くを与える

import requests 

data = requests.get("http://api.lolesports.com/api/v1/leagues?slug=worlds").json() 

は、ように見えますすべてdata["teams"]になります。スニペットがある:

[{'id': 2, 'slug': 'bangkok-titans', 'name': 'Bangkok Titans', 'teamPhotoUrl': 'http://na.lolesports.com/sites/default/files/BKT_GPL.TMPROFILE_0.png', 'logoUrl': 'http://assets.lolesports.com/team/bangkok-titans-597g0x1v.png', 'acronym': 'BKT', 'homeLeague': 'urn:rg:lolesports:global:league:league:12', 'altLogoUrl': None, 'createdAt': '2014-07-17T18:34:47.000Z', 'updatedAt': '2015-09-29T16:09:36.000Z', 'bios': {'en_US': 'The Bangkok Titans are the undisputed champions of Thailand’s League of Legends esports scene. They achieved six consecutive 1st place finishes in the Thailand Pro League from 2014 to 2015. However, they aren’t content with just domestic domination. 

各チームがリストに表示されている場合dicts:

In [1]: import requests 


In [2]: data = requests.get("http://api.lolesports.com/api/v1/leagues?slug=worlds").json() 


In [3]: for d in data["teams"]: 
    ...:   print(d["name"]) 
    ...:  
Bangkok Titans 
ahq e-Sports Club 
SK Telecom T1 
TSM 
Fnatic 
Cloud9 
Counter Logic Gaming 
H2K 
Edward Gaming 
INTZ e-Sports 
paiN Gaming 
Origen 
LGD Gaming 
Invictus Gaming 
Royal Never Give Up 
Flash Wolves 
Splyce 
Samsung Galaxy 
KT Rolster 
ROX Tigers 
G2 Esports 
I May 
Albus NoX Luna 
+0

すばらしい!ありがとう、どうしたのですか? –

2

ウェブサイトはJavaScriptを使用して読み込まれます。リクエストはJSを解釈しないため、データを解析できません。

このようなWebサイトの場合は、Seleniumでうまくいくでしょう。それはJSを含むウェブサイト全体のインタプリタとしてFirefox(または他のドライバ)を使用します。あなたはセレンを必要としない

+1

([セレン及びPhantomJSヘッドレスのWebKit介し掻き]を提供するコードhttp://pastebin.com/ 077jtNDD) – Mangohero1

+0

BernardoGoさん、ありがとう、セレンは私が必要としていたものです。 –