用python写一段爬取股票历史行情的代码
时间: 2023-05-10 20:56:09 浏览: 101
以下是一段用 Python 爬取股票历史行情的代码:
```python
import requests
import pandas as pd
def get_stock_history(stock_code):
url = 'http://quotes.money.163.com/trade/lsjysj_{}.html'.format(stock_code)
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)
response.encoding = 'utf-8'
dfs = pd.read_html(response.text)
df = dfs[3]
df.columns = ['date', 'open', 'high', 'low', 'close', 'change', 'percent', 'volume', 'amount']
df = df.drop([0, 1])
df = df.set_index('date')
return df
# 示例:获取中国平安股票历史行情
df = get_stock_history('601318')
print(df)
```
注意:这段代码仅供学习参考,不得用于商业用途。
阅读全文