【问题标题】:Scraping a school soccer results page. How do I remove \n\t from a dataframe and also combine several bs4.element.ResultSet?抓取学校足球结果页面。如何从数据框中删除 \n\t 并结合几个 bs4.element.ResultSet?
【发布时间】:2019-11-04 01:04:28
【问题描述】:

一个正在进行的项目......由一个python新手!我从学校网站创建了 4 个“类 'bs4.element.ResultSet”,称为游戏(获胜)、平局、平局和自定义。我通过抓取所有学校分数并汇总来帮助联盟。我不知道如何将这 4 个 element.resultsets 组合在一起,以便我可以运行程序的其余部分。现在它只将“游戏(获胜)”保存到 excel 电子表格中。同样在下面的输出中还有大量空格 - 我怎样才能摆脱那些 \n\t ?非常感谢您的帮助。

from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
import re

url = 'https://www.loomischaffee.org/athletics/teams/fall/soccer-boys/varsity'
page = requests.get(url)
soup = bs(page.content, 'html.parser') 

week = soup.find(id='fsEl_5138')

games = week.find_all(class_ ='fsResultWin')
draws = week.find_all(class_ ='fsResultTie')
ties = week.find_all(class_ ='fsResultLoss')
custom = week.find_all(class_ ='fsResultCustom')

# now creating 6 lists of the data contained in the above. 
date = [games.find(class_ = 'fsDate').get_text() for games in games]
time = [games.find(class_ = 'fsTime').get_text() for games in games]
opponent = [games.find(class_ = 'fsAthleticsOpponentName').get_text() for games in games]
home_away = [games.find(class_ = 'fsAthleticsAdvantage').get_text() for games in games]
location = [games.find(class_ = 'fsAthleticsLocations').get_text() for games in games]
result = [games.find(class_ = 'fsAthleticsResult').get_text() for games in games]
score = [games.find(class_ = 'fsAthleticsScore').get_text() for games in games]

# now I turn data into a table using pandas so I can manipulate

results = pd.DataFrame(
        {'Date': date,
         'Time': time,
         'Opponent': opponent,
         'Home/Away': home_away,
         'Location' : location,
         'Result': result,
         'Score': score,
         })

print(results)
results.to_excel('results.xls')

【问题讨论】:

  • 使用正则表达式替换包含 \n\t 的字符串

标签: python-3.x pandas dataframe python-requests


【解决方案1】:

你写.get_text()的地方, 你可以使用.get_text().strip() 去掉空格。

您正在存储几列, 这可能工作得很好, 如果需要,您可以将它们与zip(x, y) 结合使用。 但是你可能会发现让 BeautifulSoup 找到表格更方便, 然后在表内find_all('tr'),即遍历行。

考虑像这样表示(部分)表格行:

row = dict(opponent='vs. Northfield Mt. Hermon',
           advantage='Home',
           score='1-1')

如果你有一个 tr 对象,一个表格行,你可以很容易地找到这些值。

有了这些,您可以将整个表格表示为行列表, 每行都是dict

然后像您一直在做的那样将行输出到电子表格。 或$ pip install pandasyou can do

rows = read_html_table_rows()
df = pandas.Dataframe(rows)
df.to_excel('results.xls')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    相关资源
    最近更新 更多