简体   繁体   中英

Web-scraping w/ Python: make my web scraping code faster?

I would like to scrape two tables from 2 links. My code is:

import pandas as pd
import xlwings as xw
from datetime import datetime

def last_row(symbol, name):

    # Function that outputs if the last row of the df should be deleted or not, 
    # based on the 2 requirements below.

    requirements = [symbol.lower()=="total", name.isdigit()]
    return all(requirements)
    
    # return True, if the last row should be deleted.
    # The deletion will be performed in the next function.

def get_foreigncompanies_info():
    df_list = []
    links = ["https://stockmarketmba.com/nonuscompaniesonusexchanges.php",
              "https://stockmarketmba.com/listofadrs.php"]
    for i in links:

        #Reads table with pandas read_html and only save the necessary columns.

        df = pd.read_html(i)[0][['Symbol', 'Name', 'GICS Sector']] 
        if last_row(df.iloc[-1]['Symbol'], df.iloc[-1]['Name']):

            # Delete the last row

            df_list.append(df.iloc[:-1])
        else:

            # Keep last row

            df_list.append(df)
    return pd.concat(df_list).reset_index(drop=True).rename(columns={'Name': 'Security'})

def open_in_excel(dataframe):  # Code to view my df in excel.
    xw.view(dataframe)
    
if __name__ == "__main__":
    start = datetime.now()
    df = get_foreigncompanies_info()
    print(datetime.now() - start)
    open_in_excel(get_foreigncompanies_info())

It took在此处输入图像描述 seconds to perform the code.

I would like to make the code run faster (in a way, that doesn't make too much unnecessary request). My idea is to download the table as csv, since in the website, there is a "download csv" button.

在此处输入图像描述

How could I download the csv with python?

I have inspected the button but couldn't find the url for it. (If you can find it, please also describe how you found it perhaps with a "inspect"-screenshot.)

Or is there any other faster way to download the tables?

Thank you for any pointer:-)

You could use selenium to automate clicking on the button. It's not hard but a lot of effort for something so trivial. I don't like scraping but sometimes it's all we have, right?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM