用python爬取股票信息
时间: 2023-05-27 09:07:56 浏览: 68
以下是一个简单的Python爬虫,可以用来爬取股票信息:
```python
import requests
from bs4 import BeautifulSoup
# 股票代码
code = '600519'
# 构造URL
url = 'http://quote.eastmoney.com/sh' + code + '.html'
# 请求数据
html = requests.get(url)
soup = BeautifulSoup(html.content, 'html.parser')
# 获取股票名称
name = soup.select('#name')[0].text
print('股票名称:' + name)
# 获取当前股价
price = soup.select('.last-price')[0].text
print('当前股价:' + price)
# 获取涨跌幅
change = soup.select('.updown')[0].text
print('涨跌幅:' + change)
# 获取成交量
volume = soup.select('.large')[0].text
print('成交量:' + volume)
```
这个爬虫首先构造了一个URL,然后使用requests库发送一个GET请求来获取网页的HTML代码。接着,使用BeautifulSoup库解析HTML代码,并从中提取出股票名称、当前股价、涨跌幅和成交量等信息。最后,将这些信息打印出来。
要使用这个爬虫,只需要将股票代码替换为你要查询的股票代码即可。注意,这个爬虫只能查询A股市场的股票信息,如果要查询其他股票市场的信息,需要修改URL。