2012-06-19 51 views
0

我使用BeautifulSoup创建刮板,并请求刮擦网站的页面以获取匹配时间表(以及结果,如果可用)。这是我到目前为止有:从网站格式化刮取的数据(BeautifulSoup)

def getMatches(self): 
     url = 'http://icc-cricket.yahoo.net/match_zone/series/fixtures.php?seriesCode=ENG_WI_2012' # change seriesCode in URL for different series. 
     page = requests.get(url) 
     page_content = page.content 
     soup = BeautifulSoup(page_content) 

    result = soup.find('div', attrs={'class':'bElementBox'}) 
    tags = result.findChildren('tr') 

    for elem in tags: 
     x = elem.getText() 
     print x 

而这些结果我得到:

Date & Time (GMT)fixture 
Thu, May 17, 2012 10:00 AMEngland  vs  West Indies 
3rd TESTA full scorecard will be available shortly.Venue: Edgbaston, BirminghamResult: England won by 5 wickets 
Fri, May 25, 2012 11:00 AMEngland  vs  West Indies 
2nd TESTClick here for the full scorecardVenue: Trent Bridge, NottinghamResult:  England won by 9 wickets 
Thu, Jun 7, 2012 10:00 AMEngland  vs  West Indies 
1st TESTClick here for the full scorecardVenue: Lord'sResult: Match Drawn 
Sat, Jun 16, 2012 9:45 AMEngland  vs  West Indies 
1st ODIClick here for the full scorecardVenue: The Rose Bowl, SouthamptonResult:  England won by 114 runs (D/L Method) 
Tue, Jun 19, 2012 9:45 AMEngland  vs  West Indies 
2nd ODIVenue: KIA Oval 
Fri, Jun 22, 2012 9:45 AMEngland  vs  West Indies 
3rd ODIVenue: Headingley Carnegie 
Sun, Jun 24, 2012 12:00 AMEngland  vs  West Indies 
1st T20Venue: Trent Bridge, Nottingham 

现在,我想在一些结构化的格式对数据进行分类。一个包含
关于一场比赛的信息列表将是理想的。但我坚持如何实现这一目标。结果中的输出字符串具有像&nbsp这样的字符,并且时间奇怪地排列,如AMEngland。还有一个问题是,如果我用空格字符作为分隔符来分割字符串,像西印度群岛这样的国家将会被分割,并且将不会有任何统一的方式来解析它。

那么有没有一种方法可以统一解析这些数据,所以我可以在表单中找到。有点像:

[ {'date': match_date, 'home_team': team1, 'away_team': team2, 'venue': venue},{ same for match 2}, { match 3 }...] 

我会感谢任何帮助。 :)

回答

1

这是不是很难分开日期/时间和国家。你可以为“Venue”和“Result”做同样的事情。

>>> import re 
>>> s = "Sun, Jun 24, 2012 12:00 AMEngland  vs  West Indies" 
>>> match = re.search(r"\b[AP]M", s) 
>>> s[0:match.end()] 
'Sun, Jun 24, 2012 12:00 AM' 
>>> s[match.end():] 
'England  vs  West Indies' 
+0

非常感谢。我想整天看HTML会让我有点忘记我只能用一个简单的正则表达式。 :) –

0

改为看看scrapy;它会使这项任务变得更容易。

您定义items从该网站刮:

from scrapy.item import Item, Field 

class CricketMatch(Item): 
    date = Field() 
    home_team = Field() 
    away_team = Field() 
    venue = Field() 

然后定义loader with XPath expressions填写这些项目。之后,您可以直接使用这些物品,或produce JSON output or similar

+0

我确实要去scrapy,但我正在使用的应用程序已经使用BeautifulSoup来处理现有的任务,所以我被告知不要使用它。 –

+0

不幸的是,你没有在你的问题中指定。另外请注意,SO旨在提供一般有用的问题和答案,而不仅仅是针对个别案例,所以我会留下我的答案。 –