酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

用python爬取东方财富沪深京行业板块第一页股票数据并保存到本地.

您可以使用Python中的requests库和BeautifulSoup库来爬取东方财富网站的数据,并使用pandas库将数据保存到本地。 首先,安装必要的库: ``` pip install requests pip install BeautifulSoup4 pip install pandas ``` 然后,编写以下代码: ```python import requests from bs4 import BeautifulSoup import pandas as pd # 发送HTTP GET请求获取页面内容 url = 'http://quote.eastmoney.com/center/gridlist.html#hs_a_board' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) html = response.text # 使用BeautifulSoup解析页面内容 soup = BeautifulSoup(html, 'html.parser') # 找到股票数据所在的表格 table = soup.find('table', class_='tab1') # 创建一个空的DataFrame来保存数据 data = pd.DataFrame(columns=['股票代码', '股票名称', '最新价', '涨跌幅']) # 遍历表格的每一行,提取股票数据 for row in table.find_all('tr')[1:]: cells = row.find_all('td') code = cells[1].text.strip() name = cells[2].text.strip() price = cells[3].text.strip() change = cells[4].text.strip() data = data.append({'股票代码': code, '股票名称': name, '最新价': price, '涨跌幅': change}, ignore_index=True) # 将数据保存到本地 data.to_excel('stock_data.xlsx', index=False) print('数据已保存到stock_data.xlsx') ``` 运行以上代码,会在当前目录下生成一个名为stock_data.xlsx的Excel文件,其中包含了东方财富网站沪深京行业板块第一页股票的数据。 [2024-11-26 22:36:37 | AI写代码神器 | 976点数解答]

相关提问