一個網(wǎng)頁中有一個很長的表格,要提取其全部內(nèi)容,還有表格中的所有URL網(wǎng)址。 ![]() 在kimi中輸入提示詞: 你是一個Python編程專家,要完成一個編寫爬取網(wǎng)頁表格內(nèi)容的Python腳步的任務,具體步驟如下: 在F盤新建一個Excel文件:freeAPI.xlsx 打開網(wǎng)頁https://github.com/public-apis/public-apis; 定位table標簽; 在table標簽內(nèi)容定位tbody標簽; 在tbody標簽內(nèi)定位tr標簽; 在tr標簽內(nèi)容定位第1個td標簽,提取其文本內(nèi)容,保存到表格文件freeAPI.xlsx的第1行第1列; 在tr標簽內(nèi)容定位第1個td標簽里面的a標簽,提取其href屬性值,保存到表格文件freeAPI.xlsx的第1行第6列; 在tr標簽內(nèi)容定位第2個td標簽,提取其文本內(nèi)容,保存到表格文件freeAPI.xlsx的第1行第2列; 在tr標簽內(nèi)容定位第3個td標簽,提取其文本內(nèi)容,保存到表格文件freeAPI.xlsx的第1行第3列; 在tr標簽內(nèi)容定位第4個td標簽,提取其文本內(nèi)容,保存到表格文件freeAPI.xlsx的第1行第4列; 在tr標簽內(nèi)容定位第5個td標簽,提取其文本內(nèi)容,保存到表格文件freeAPI.xlsx的第1行第5列; 循環(huán)執(zhí)行以上步驟,直到所有table標簽里面內(nèi)容都提取完; 注意: 每一步相關(guān)信息都要輸出到屏幕上 ![]() 源代碼: import requests from bs4 import BeautifulSoup import pandas as pd # 網(wǎng)頁URL url = 'https://github.com/public-apis/public-apis' # 發(fā)送HTTP請求獲取網(wǎng)頁內(nèi)容 response = requests.get(url) web_content = response.text # 使用BeautifulSoup解析網(wǎng)頁 soup = BeautifulSoup(web_content, 'html.parser') # 定位所有的table標簽 tables = soup.find_all('table') # 檢查F盤是否存在freeAPI.xlsx文件,如果不存在則創(chuàng)建 excel_path = 'F:/freeAPI.xlsx' df_list = [] # 用于存儲DataFrame的列表 for table in tables: # 定位tbody標簽 tbody = table.find('tbody') if tbody: # 在tbody標簽內(nèi)定位所有的tr標簽 rows = tbody.find_all('tr') for row in rows: # 在每個tr標簽內(nèi)定位所有的td標簽 data = row.find_all('td') if len(data) >= 5: # 提取文本內(nèi)容 extracted_data = [cell.get_text(strip=True) for cell in data[:5]] # 將提取的數(shù)據(jù)存儲為DataFrame df = pd.DataFrame([extracted_data], columns=['Column1', 'Column2', 'Column3', 'Column4', 'Column5']) # 將DataFrame添加到列表中 df_list.append(df) # 輸出相關(guān)信息到屏幕 print(f"Extracted data from row: {extracted_data}") # 將列表中的所有DataFrame合并為一個DataFrame if df_list: combined_df = pd.concat(df_list, ignore_index=True) # 將合并后的DataFrame寫入Excel文件 combined_df.to_excel(excel_path, index=False) print(f"Data has been successfully written to {excel_path}") else: print("No data found to write to Excel.") ![]() |
|