0

웹 사이트에서 표를 긁어 내려고했습니다. 실행되지만 내 파일로 출력되지 않습니다. 내가 어디로 잘못 가고 있니?웹 스크래퍼 코드 (python3.4)의 문제점

코드 :

from bs4 import BeautifulSoup 

import urllib.request 

f = open('nbapro.txt','w') 
errorFile = open('nbaerror.txt','w') 

page = urllib.request.urlopen('http://www.numberfire.com/nba/fantasy/full-fantasy-basketball-projections') 

content = page.read() 
soup = BeautifulSoup(content) 

tableStats = soup.find('table', {'class': 'data-table xsmall'}) 
for row in tableStats.findAll('tr')[2:]: 
col = row.findAll('td') 

try: 
    name = col[0].a.string.strip() 
    f.write(name+'\n') 
except Exception as e: 
    errorFile.write (str(e) + '******'+ str(col) + '\n') 
    pass 

f.close 
errorFile.close 

답변

1

문제는 당신이 긁어하려고하는 테이블 데이터가 브라우저 측에 자바 스크립트 코드를 호출하여 작성된다는 점이다. urllib는 브라우저가 아니므로 javascript를 실행할 수 없습니다.

urllibBeautifulSoup를 통해 그것을 해결하려면

, 당신은 script 태그에서 JSON 객체를 추출하고 json.loads()를 통해로드해야합니다. 예 : 플레이어 이름을 인쇄합니다.

import json 
import re 
import urllib.request 
from bs4 import BeautifulSoup 


soup = BeautifulSoup(urllib.request.urlopen('http://www.numberfire.com/nba/fantasy/full-fantasy-basketball-projections')) 

script = soup.find('script', text=lambda x: x and 'NF_DATA' in x).text 
data = re.search(r'NF_DATA = (.*?);', script).group(1) 
data = json.loads(data) 

for player_id, player in data['players'].items(): 
    print(player['name'] + ' ' + player['last_name']) 
+0

위대한 사람 감사합니다 ... 이제 작동하고 있습니다. –

+0

이제이 코드를 연구하고 이해해야합니다. –