BeautifulSoup数据抓取和数据库

时间:2014-10-21 18:25:35

标签: python sql sqlite web-scraping beautifulsoup

我使用BeautifulSoup来解析网站。

现在我的问题如下:我想把所有这些写进一个DB(比如sqlite),其中包含一个目标的分钟数(这个信息我可以从我得到的链接中得到)但这是可能的仅在目标数不是? - ?的情况下,因为没有任何目标。

from pprint import pprint
import urllib2

from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.livescore.com/soccer/champions-league/'))

data = []
for match in soup.select('table.league-table tr'):
    try:
        team1, team2 = match.find_all('td', class_=['fh', 'fa'])
    except ValueError:  # helps to skip irrelevant rows
        continue

    score = match.find('a', class_='scorelink').text.strip()
    data.append({
        'team1': team1.text.strip(),
        'team2': team2.text.strip(),
        'score': score
    })

pprint(data)

href_tags = soup.find_all('a', {'class':"scorelink"})

links = []

for x in xrange(1, len(href_tags)):
    insert = href_tags[x].get("href");links.append(insert)

print links

1 个答案:

答案 0 :(得分:1)

首先,如果没有参加比赛中的球队,那么得分会有什么意义呢?

这个想法是迭代每个具有league-table类的表中的每一行。对于每一行,获取团队名称和分数。将结果收集到词典列表中:

from pprint import pprint
import urllib2

from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.livescore.com/soccer/champions-league/'))

data = []
for match in soup.select('table.league-table tr'):
    try:
        team1, team2 = match.find_all('td', class_=['fh', 'fa'])
    except ValueError:  # helps to skip irrelevant rows
        continue

    score = match.find('a', class_='scorelink').text.strip()
    data.append({
        'team1': team1.text.strip(),
        'team2': team2.text.strip(),
        'score': score
    })

pprint(data)

打印:

[
    {'score': u'? - ?', 'team1': u'Atletico Madrid', 'team2': u'Malmo FF'},
    {'score': u'? - ?', 'team1': u'Olympiakos', 'team2': u'Juventus'},
    {'score': u'? - ?', 'team1': u'Liverpool', 'team2': u'Real Madrid'},
    {'score': u'? - ?', 'team1': u'PFC Ludogorets Razgrad', 'team2': u'Basel'},
    ...
]

请注意,目前它会追加每场比赛,即使它尚未播放。如果您需要收集具有分数的匹配项,您只需检查score是否不等于? - ?

if score != '? - ?':
    data.append({
        'team1': team1.text.strip(),
        'team2': team2.text.strip(),
        'score': score
    })

这种情况下的输出是:

[{'score': u'2 - 2', 'team1': u'CSKA Moscow', 'team2': u'Manchester City'},
 {'score': u'3 - 0', 'team1': u'Zenit St. Petersburg', 'team2': u'Standard Liege'},
 {'score': u'4 - 0', 'team1': u'APOEL Nicosia', 'team2': u'AaB'},
 {'score': u'3 - 0', 'team1': u'BATE Borisov', 'team2': u'Slovan Bratislava'},
 {'score': u'0 - 1', 'team1': u'Celtic', 'team2': u'Maribor'},
 {'score': u'2 - 0', 'team1': u'FC Porto', 'team2': u'Lille'},
 {'score': u'1 - 0', 'team1': u'Arsenal', 'team2': u'Besiktas'},
 {'score': u'3 - 1', 'team1': u'Athletic Bilbao', 'team2': u'SSC Napoli'},
 {'score': u'4 - 0', 'team1': u'Bayer Leverkusen', 'team2': u'FC Koebenhavn'},
 {'score': u'3 - 0', 'team1': u'Malmo FF', 'team2': u'Salzburg'},
 {'score': u'1 - 0', 'team1': u'PFC Ludogorets Razgrad *', 'team2': u'Steaua Bucuresti'}]

至于#34;写入数据库"另外,您可以使用sqlite3模块和executemany()named parameters

import sqlite3

conn = sqlite3.connect('data.db')
conn.execute("""
    CREATE TABLE IF NOT EXISTS matches (
        id    integer primary key autoincrement not null,
        team1  text,
        team2 text,
        score text
    )""")

cursor = conn.cursor()
cursor.executemany("""
    INSERT INTO 
        matches (team1, team2, score) 
    VALUES 
        (:team1, :team2, :score)""", data)
conn.commit()
conn.close()

当然还有其他一些需要改进或谈论的事情,但我认为这对你来说是一个好的开始。