【问题标题】:Eliminate % Symbol While Using Selenium Scraper (Python)使用 Selenium Scraper (Python) 时消除 % 符号
【发布时间】:2018-11-24 19:32:03
【问题描述】:

下面是一个 selenium 网络爬虫,它会循环浏览本网站页面 (https://www.fangraphs.com/leaders.aspx?pos=all&stats=bat&lg=all&qual=y&type=8&season=2018&month=0&season1=2018&ind=0) 的不同选项卡,选择“导出数据”按钮,下载数据,添加 yearid 列,然后将数据加载到 MySQL 表中.

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()

刮板工作完美,但是,当我下载数据时,某些列下载的数据在整数(即 25%)后带有 % 符号,这会影响我在 MySQL 中的格式。将数据抓取到 Pandas 数据框中时,是否可以更改包含 % 符号的列,使其仅显示整数?如果是这样,我将如何在我创建的循环中实现这一点,以从网站上的各个选项卡中抓取数据?我还想从这个过程中排除第一行数据,因为那是我保留列名的行。提前致谢!

【问题讨论】:

    标签: python mysql pandas selenium web-scraping


    【解决方案1】:

    在您抓取所有内容并将其放入 pandas 数据框中后,您可以将所有 % 符号替换为 replace

    df.replace('%','')
    

    【讨论】:

    • 感谢您的回复!不幸的是,那没有用。您认为我需要将其合并到循环中吗?谢谢!
    • 您应该使用df=df.replace('%','')df.replace('%','',inplace=True)
    • 谢谢,DyZ!不幸的是,百分比符号仍然显示在 CSV 和数据库文件中。你认为我需要将它合并到循环中吗?
    【解决方案2】:

    使用Pandas.Series.str.replace()

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

    【讨论】:

    • 感谢萨希尔的回复!不幸的是,我不断收到错误消息“数据框对象没有字符串”。有什么想法吗?
    • 嗯...好的。您愿意使用 CSV 模块吗?
    • 只要我能够直接将 CSV 导出到我的 MySQL 数据库中,我可以接受任何建议。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多