用python 爬取股票代码
时间: 2023-07-17 14:52:31 浏览: 52
当然可以!以下是使用Python爬取股票代码的示例代码:
```python
import requests
from bs4 import BeautifulSoup
def get_stock_codes():
url = 'http://quote.eastmoney.com/stocklist.html' # 股票代码网址
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
codes = []
for a_tag in soup.find_all('a'):
code = a_tag.get('href')
if code and code.startswith('http://quote.eastmoney.com/'):
code = code.split('/')[-1].split('.')[0]
codes.append(code)
return codes
stock_codes = get_stock_codes()
print(stock_codes)
```
这段代码使用requests库发送HTTP请求,然后使用BeautifulSoup库解析HTML文档。通过分析网页结构,我们可以提取股票代码。在这个例子中,我们使用东方财富网的股票代码页面作为示例。你也可以根据需要修改代码来适应其他网站的股票代码提取。
相关问题
用python 爬取股票代码,获取到数据后,整理成EXCEL
可以使用Python中的requests库来爬取股票代码数据,并使用pandas库将数据整理成Excel文件。以下是一个示例代码:
```python
import requests
import pandas as pd
def get_stock_codes():
url = 'http://example.com/stock_codes' # 替换为实际的股票代码数据源链接
response = requests.get(url)
# 解析网页内容并提取股票代码数据
# 这里假设股票代码数据以逗号分隔,并存储在response.text中
stock_codes = response.text.split(',')
return stock_codes
def save_to_excel(stock_codes):
# 创建一个DataFrame对象,以股票代码为列名
df = pd.DataFrame({'Stock Code': stock_codes})
# 将DataFrame保存为Excel文件
df.to_excel('stock_codes.xlsx', index=False)
# 程序入口
if __name__ == '__main__':
stock_codes = get_stock_codes()
save_to_excel(stock_codes)
```
在上面的示例代码中,你需要替换`url`变量为实际的股票代码数据源链接。爬取的股票代码数据假设以逗号分隔,并存储在`response.text`中。你可以根据实际情况修改代码来适配数据源的格式。
运行该代码后,将会在当前目录下生成名为`stock_codes.xlsx`的Excel文件,其中包含了整理好的股票代码数据。
python爬取股票数据代码
以下是一个简单的 Python 爬取股票数据的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 定义股票代码
stock_code = '600519'
# 构造请求URL
url = f'http://quote.eastmoney.com/{stock_code}.html'
# 发送请求并获取HTML内容
response = requests.get(url)
html = response.content.decode('gbk')
# 解析HTML内容
soup = BeautifulSoup(html, 'html.parser')
# 获取股票名称
stock_name = soup.select_one('.name').text.strip()
# 获取当前股价
stock_price = soup.select_one('.price').text.strip()
# 输出结果
print(f'{stock_name}({stock_code}) 当前股价为 {stock_price} 元。')
```
在这个示例中,我们使用了 requests 库发送 HTTP 请求,并使用 BeautifulSoup 库解析 HTML 内容,从而获取股票名称和当前股价。请注意,股票代码需要根据具体情况进行修改。