Eliminate % Symbol While Using Selenium Scraper (Python)

我只是一个虾纸丫 提交于 2019-12-02 17:21:31

问题


Below is a selenium web scraper that loops through the different tabs of this website page (https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=y&type=8&season=2018&month=0&season1=2018&ind=0), selects the "export data" button, downloads the data, adds a yearid column, then loads the data into a MySQL table.

import sys
import pandas as pd
import os
import time
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from sqlalchemy import create_engine


button_text_to_url_type = {
    'dashboard': 8,
    'standard': 0,
     'advanced': 1,
     'batted_ball': 2,
     'win_probability': 3,
     'pitch_type': 4,
     'pitch_values': 7,
     'plate_discipline': 5,
     'value': 6
}

download_dir = os.getcwd()
profile = FirefoxProfile("C:/Users/PATHTOFIREFOX")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", 'text/csv')
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference("browser.download.dir", download_dir)
profile.set_preference("browser.download.folderList", 2)
driver = webdriver.Firefox(firefox_profile=profile)


today = datetime.today()
for button_text, url_type in button_text_to_url_type.items():

    default_filepath = os.path.join(download_dir, 'Fangraphs Leaderboard.csv')
    desired_filepath = os.path.join(download_dir,
                                    '{}_{}_{}_Leaderboard_{}.csv'.format(today.year, today.month, today.day,
                                                                         button_text))

    driver.get(
        "https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=0&type={}&season=2018&month=0&season1=2018&ind=0&team=&rost=&age=&filter=&players=".format(
            url_type))
    driver.find_element_by_link_text('Export Data').click()
    if os.path.isfile(default_filepath):
        os.rename(default_filepath, desired_filepath)
        print('Renamed file {} to {}'.format(default_filepath, desired_filepath))
    else:
        sys.exit('Error, unable to locate file at {}'.format(default_filepath))

    df = pd.read_csv(desired_filepath)
    df["yearid"] = datetime.today().year
    df.to_csv(desired_filepath)

    engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
                           .format(user="walker",
                                   pw="password",
                                   db="data"))
    df.to_sql(con=engine, name='fg_test_hitting_{}'.format(button_text), if_exists='replace')

time.sleep(10)
driver.quit()

The scraper works perfectly, however, when I download the data, some columns download data with a % sign after an integer (i.e., 25%) which throws off my formatting in MySQL. When scraping the data into a Pandas data frame, is it possible to alter the columns that contain the % symbol so that it just shows the integer? If so, how would I implement this in the loop I created to scrape data from the various tabs on the website? I would also like to exclude the first row of data from this process since that is the row where I keep my column names. Thanks in advance!


回答1:


After you scrape everything and have it in a pandas dataframe, you can just replace all % signs with replace.

df.replace('%','')



回答2:


Use Pandas.Series.str.replace().

df.str.replace('%','')


来源:https://stackoverflow.com/questions/50867356/eliminate-symbol-while-using-selenium-scraper-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!