2016-07-25 84 views
0

我想用BS4和Python 2.7从http://www.pro-football-reference.com/boxscores/201602070den.htm刮掉“团队统计”表格。但是林无法得到任何接近它,用Python/BS4刮脸

url = 'http://www.pro-football-reference.com/boxscores/201602070den.htm' 
page = requests.get(url) 
soup = BeautifulSoup(page.text, "html5lib") 
table=soup.findAll('table', {'id':"team_stats", "class":"stats_table"}) 
print table 

我觉得像上面的代码会工作,但没有运气。

+0

你到底要刮?桌子? –

+1

为了获得有效的帮助,您需要提供更多的信息(在您的原始文章中,而不是在可能无法看到的评论中)。不工作:不运行?或者,运行,但给出不正确的结果?你在期待什么?发生什么事?还包括任何错误消息(如果适用)。此外,看起来像你缺少一些'进口'陈述 – Levon

+0

其装载的JavaScript ...所以你将需要像ghost.js或硒somertign ... –

回答

1

这种情况下的问题是“Team Stats”表格位于您使用requests下载的HTML源代码中的评论内。找到注释,并用BeautifulSoup重新分析它变成一个“汤”对象:

import requests 
from bs4 import BeautifulSoup, NavigableString 

url = 'http://www.pro-football-reference.com/boxscores/201602070den.htm' 
page = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}) 

soup = BeautifulSoup(page.content, "html5lib") 
comment = soup.find(text=lambda x: isinstance(x, NavigableString) and "team_stats" in x) 

soup = BeautifulSoup(comment, "html5lib") 
table = soup.find("table", id="team_stats") 
print(table) 

和/或可以加载表入里,例如pandas dataframe这是非常方便与合作:

import pandas as pd 
import requests 
from bs4 import BeautifulSoup 
from bs4 import NavigableString 

url = 'http://www.pro-football-reference.com/boxscores/201602070den.htm' 
page = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'}) 

soup = BeautifulSoup(page.content, "html5lib") 
comment = soup.find(text=lambda x: isinstance(x, NavigableString) and "team_stats" in x) 

df = pd.read_html(comment)[0] 
print(df) 

打印:

  Unnamed: 0   DEN   CAR 
0   First Downs    11    21 
1   Rush-Yds-TDs  28-90-1  27-118-1 
2 Cmp-Att-Yd-TD-INT 13-23-141-0-1 18-41-265-0-1 
3   Sacked-Yards   5-37   7-68 
4  Net Pass Yards   104   197 
5   Total Yards   194   315 
6   Fumbles-Lost   3-1   4-3 
7   Turnovers    2    4 
8  Penalties-Yards   6-51   12-102 
9  Third Down Conv.   1-14   3-15 
10 Fourth Down Conv.   0-0   0-0 
11 Time of Possession   27:13   32:47 
+0

哇它会花我一段时间了解这里发生了什么哈哈谢谢。 –