2017-10-07 10 views
1

私はPythonの初心者です。今すぐ始めましょう。
私のシステム環境はPython 3.5で、一部のライブラリはWindows10です。JSON/WebページのJavascriptからデータをスクラップする方法は?

私は下のサイトからフットボールのプレーヤーデータをCSVファイルとして抽出したいと思います。

問題soup.find_all('script')[17]から予想されるCSV形式にデータを抽出できません。それらのデータをどのように抽出したいのですか?

私のコードは以下の通りです。

from bs4 import BeautifulSoup 
import re 
from urllib.request import Request, urlopen 

req = Request('http://www.futhead.com/squad-building-challenges/squads/343', headers={'User-Agent': 'Mozilla/5.0'}) 
webpage = urlopen(req).read() 
soup = BeautifulSoup(webpage,'html.parser') #not sure if i need to use lxml 
soup.find_all('script')[17] #My target data is in 17th 

私の予想出力はだから私の理解がbeautifulsoupは、HTMLの構文解析のためのより良いですが、HTMLにネストされたJavaScriptを解析しようとしているということである。この

position,slot_position,slug 
ST,ST,paulo-henrique 
LM,LM,mugdat-celik 
+0

あなたの質問と問題はどこですか? – Thecave3

答えて

0

@josiahスウェインは言ったように、それほど美しくはありません。このようなことについては、あなたが持っているものを理解できるようにJSを使用することをお勧めします。

これは、Pythonは素晴らしいとここにあなたのソリューションですと言って!

#Same imports as before 
from bs4 import BeautifulSoup 
import re 
from urllib.request import Request, urlopen 

#And one more 
import json 

# The code you had 
req = Request('http://www.futhead.com/squad-building-challenges/squads/343', 
       headers={'User-Agent': 'Mozilla/5.0'}) 
webpage = urlopen(req).read() 
soup = BeautifulSoup(webpage,'html.parser') 

# Store the script 
script = soup.find_all('script')[17] 

# Extract the oneline that stores all that JSON 
uncleanJson = [line for line in script.text.split('\n') 
     if line.lstrip().startswith('squad.register_players($.parseJSON') ][0] 

# The easiest way to strip away all that yucky JS to get to the JSON 
cleanJSON = uncleanJson.lstrip() \ 
         .replace('squad.register_players($.parseJSON(\'', '') \ 
         .replace('\'));','') 

# Extract out that useful info 
data = [ [p['position'],p['data']['slot_position'],p['data']['slug']] 
     for p in json.loads(cleanJSON) 
     if p['player'] is not None] 


print('position,slot_position,slug') 
for line in data: 
    print(','.join(line)) 

私はコピーのために取得してのpythonにこれを貼り付けた結果は次のとおりです。

position,slot_position,slug 
ST,ST,paulo-henrique 
LM,LM,mugdat-celik 
CAM,CAM,soner-aydogdu 
RM,RM,petar-grbic 
GK,GK,fatih-ozturk 
CDM,CDM,eray-ataseven 
LB,LB,kadir-keles 
CB,CB,caner-osmanpasa 
CB,CB,mustafa-yumlu 
RM,RM,ioan-adrian-hora 
GK,GK,bora-kork 

編集:反射では、これは初心者のために読むための最も簡単なコードではありません。ここでは、より読みやすいバージョンです

# ... All that previous code 
script = soup.find_all('script')[17] 

allScriptLines = script.text.split('\n') 

uncleanJson = None 
for line in allScriptLines: 
    # Remove left whitespace (makes it easier to parse) 
    cleaner_line = line.lstrip() 
    if cleaner_line.startswith('squad.register_players($.parseJSON'): 
      uncleanJson = cleaner_line 

cleanJSON = uncleanJson.replace('squad.register_players($.parseJSON(\'', '').replace('\'));','') 

print('position,slot_position,slug') 
for player in json.loads(cleanJSON): 
    if player['player'] is not None: 
     print(player['position'],player['data']['slot_position'],player['data']['slug']) 
+0

これはうまくいきます。この問題を解決する方法について私に説明してくれてありがとう、ありがとう。あなたのコードを読んだら、初心者にとってPythonを学ぶのは簡単ではありません。 – nisahc

0

と同様です。

だから、あなたは、単に[17]soup.find_all(「スクリプト」)の結果を取る関数を二つのオプション

  1. を作成している、ループやデータの手動文字列を検索し、それを抽出。さらに簡単にするためにast.literal_eval(string_thats_really_a_dictionary)を使用することもできます。これは最善の方法ではないかもしれませんが、あなたがPythonを初めて使用している場合は、これを練習のためだけにしたいかもしれません。
  2. Use the json library like in this example.またはalternatively like this way.これはおそらく良い方法です。
+0

この問題のサンプルコードを教えてください。 – nisahc

関連する問題