用python写一个爬取股票的代码
以下是一个简单的股票爬虫代码,可以爬取东方财富网的股票数据:
import requests
from bs4 import BeautifulSoup
def get_stock_info(stock_code):
url = 'http://quote.eastmoney.com/{}.html'.format(stock_code)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
name = soup.find('a', class_='name').text
price = soup.find('span', class_='price').text
change_percent = soup.find('span', class_='change-percent').text
return {'name': name, 'price': price, 'change_percent': change_percent}
if __name__ == '__main__':
stock_code = 'sh600519'
stock_info = get_stock_info(stock_code)
print(stock_info)
该代码使用了requests库和BeautifulSoup库来爬取股票数据。具体实现过程如下:
-
构造股票页面的URL,并使用requests库发送GET请求获取页面内容。
-
使用BeautifulSoup库解析页面内容,找到目标元素。
-
提取目标元素的文本信息,并以字典形式返回。
-
在主函数中调用get_stock_info函数,并打印返回值。
需要注意的是,该代码只能爬取东方财富网的股票数据,如果需要爬取其他网站的股票数据,需要根据不同网站的HTML结构进行相应的修改。同时,在实际使用中要注意网络爬虫的法律风险和道德风险,遵守相关规定和道德准则。
原文地址: https://www.cveoy.top/t/topic/bJux 著作权归作者所有。请勿转载和采集!