爬虫—根据股票代码实时抓取股票信息
数据来源网址:https://xueqiu.com
目标:根据输入的股票代码和证券所,实时抓取股票的交易信息
源码如下:
import requests
from lxml import etree
# 本案例数据需要账号登录之后才能获取,所以headers头部应该加cookie键值对
headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Cookie': 'cookiesu=291705301257305; Hm_lvt_1db88642e346389874251b5a1eded6e3=1705301259; device_id=c0922624cb0c519d46f69c7e06d1b22c; s=a811kg480v; xq_a_tokenBuNEFadXAifQ.Fmf0Pzni2S1B9cjrrgO9JGfxXhxAcLoof_mXLwdBWiqNIzbzBxcnIFGxlJ81OANkwKcVYypwaKAHBJRDiEfnip8eh_ZMUyR48M76yOLAsnWfHve_uNP-muPRA-_mA2vf5UdLQbbIUZQox0a3xT6YzJbqIrh90rpcCyPb940gcKp6S-8Z76iOyLc943Panm3rJv_NVEdrEuXrQm9K7-17XN6KfbKaHkC1uGInssZnJunYf4P536OLT3rp96XcoBnC5zZp1N869kJINMDryIh5TTdZnqdIOPORY0ZWY-Vjm3phZKB_4drmROP-L_1H4vOn5ueJSkkN9UGb3xvTd1qOZQ; xq_is_login=1; u=1984380207; snbim_minify=true; __utma=1.618845020.1705302340.1705302340.1705302340.1; __utmc=1; __utmz=1.1705302340.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); acw_tc=2760825c17053658496137472ec8319963809c48b0f5d01ae56d064ff36917; Hm_lpvt_1db88642e346389874251b5a1eded6e3=170536619'}
# 定义一个函数,参数为股票代码和证券交易类型
def get_stock_info(stock_code, stock_type):
url = f'https://xueqiu.com/S/{stock_type + stock_code}'
res = requests.get(url, headers=headers)
if res.status_code == 200:
res.encoding = res.apparent_encoding
data = res.content.decode()
tree = etree.HTML(data)
td_lst = tree.xpath('//div[@class="quote-container"]//table[@class="quote-info"]/tr//td')
stock_name = tree.xpath('//div[@class="stock-name"]/text()')
stock_current_price = tree.xpath('//div[@class="stock-current"]')[0]
stock_change = tree.xpath('//div[@class="stock-change"]')[0]
print('股票名称及代码:', stock_name[0])
print('股票当前股价:', stock_current_price.xpath('./strong/text()')[0], '股票当前波动:', stock_change.xpath('./text()')[0])
print('股票的详细信息:')
for td in td_lst:
print(' '.join(td.xpath('.//text()')))
else:
print('请核实查询的股票代码和证券公司类型!')
if __name__ == '__main__':
stock_code = input('请输入要查询的股票代码: ')
stock_type = input('请输入证券交易所(SZ|SH):').upper()
get_stock_info(stock_code, stock_type)
截图所示: