0
我有一個函數,(1)從每個包含表數據的URL列表中刪除數據。它使用BeautifulSoup刮取html文本以收集包含列標題和表格行的單獨列表。然後它(2)遍歷錶行列表以創建列表列表。最後,(3)我在for循環中遍歷URL列表中的函數。在函數編譯完列表的列表後,可以將列標題行添加到函數內的列表列表中嗎?
我遇到的問題是我無法弄清楚如何將我的列標題插入到我的數據中,使列標題出現在最終的數據框中。我應該追加/插入列標題到函數內的輸出列表?或者有沒有辦法將其插入數據框? (因爲COLUMN_HEADERS變量是本地的功能,因此不能作爲一個全局變量我不能插入列標題到函數後的數據幀
這裏基本上是我到目前爲止有:。
my_list_of_urls = [a, list, of, several, urls]
def scraper_from_URL_list(url_parameter):
# get the html
html = urlopen(url_parameter)
# create the BeautifulSoup object
soup = BeautifulSoup(html, "lxml")
column_headers = [CSS SELECTOR GADGET TO GET COLUMN HEADER DATA]
table_rows = soup.select(CSS SELECTOR GADGET TO GET TABLE ROW DATA)
output_list = []
for row in table_rows:
table_data_output = [COMMAND TO CONVERT TABLE ROW VARIABLE INTO AN ORGANIZED LIST OF LISTS
output_list.append(table_data_output)
return output_list
#To call the function and iterate through list of URLs to output it to a dataframe
df_output_list = pd.DataFrame()
for url in my_list_of_urls:
df_output = pd.concat([df_output, pd.DataFrame(scrape_sports_stats(url))])
您可以使用'''pd.read_html()'''而不是創建列表清單 - [文檔鏈接](https://pandas.pydata.org/pandas-docs/stable/generated /pandas.read_html.html),並使用'''DataFrame'''對象的''''''''''屬性將列添加到數據框中 - https://stackoverflow.com/q/11346283/2650427 – TrigonaMinima