php 爬取股票数据库,【实例】--股票数据定向爬取

从股票列表网页获取股票代码

根据股票代码去股票详情页面获取股票详细信息

1、 股票列表页面

凤凰网财经—股票信息

http://app.finance.ifeng.com/list/stock.php?t=ha&f=chg_pct&o=desc&p=1

2、 股票详细信息

老虎社区—股票详情

股票数据定向爬取思路

1、 查看网站robots协议,查看网站是否可以爬取

2、 查看网页源代码,查看网页信息是否可以直接爬取

3、 爬取网页信息

4、 解析网页,获取页面信息

在HTML页面中

1)      对于非常有特征的数据,可以直接用正则表达式搜索到

2)      信息存在的区域相对固定,则用BeautifulSoup定位标签位置,再用正则表达式获取

5、 将获取的信息储存到文件中

优化代码

1、提高爬虫速度

直接赋值编码

2、提高程序运行体验(运行时间较长的程序)

增加动态精度显示

import requests

from bs4 import BeautifulSoup

import re

import traceback

def getHTMLText(url, code=‘utf-8‘):

try:

r = requests.get(url)

r.raise_for_status()

r.encoding = code

return r.text

except:

print(‘爬取失败‘)

def getStockList(lst, stockURL):

html = getHTMLText(stockURL, ‘GB2312‘)

soup = BeautifulSoup(html, ‘html.parser‘)

a = soup.find_all(‘a‘)

for i in a:

try:

href = i.attrs[‘href‘]

lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) ## 匹配 a 标签中 href 属性以 s 开头,中间是 h 或 z ,最后是6位数字

except:

continue

def getStockInfo(lst, stockURL, fpath):

## 去掉列表里的重复选项--将列表转换为集合再转换为列表

lst = list(set(lst))

count = 0

for stock in lst:

url = stockURL + stock[-6:]

html = getHTMLText(url)

try:

if html == ‘‘: ## 判断是否空页面

continue

infoDict = {} ## 定义一个字典,存储股票信息

soup = BeautifulSoup(html, ‘html.parser‘)

stockInfo = soup.find(‘div‘, attrs={‘class‘:‘stock-info‘})

name = stockInfo.find_all(attrs={‘class‘:‘name‘})[0]

price = stockInfo.find_all(attrs={‘class‘: ‘latest‘})[0]

infoDict.update({‘股票名称‘:name.text.split()[0], ‘最新行情‘:price.text.split()[0]})

keyList = stockInfo.find_all(‘dt‘)

valueList = stockInfo.find_all(‘dd‘)

for i in range(len(keyList)):

key = keyList[i].text

val = valueList[i].text

infoDict[key] = val

## 将字典写入文件中

with open(fpath, ‘a‘, encoding=‘utf-8‘) as f:

f.write(str(infoDict) + ‘\n‘)

count = count + 1

## 增加动态进度显示

print(‘\r当前进度:{:.2f}%‘.format(count*100/len(lst)), end=‘‘)

except:

traceback.print_exc() ## 获得发生异常的错误信息

continue

def main():

stock_list_url = ‘http://app.finance.ifeng.com/list/stock.php?t=ha‘

stock_info_url = ‘https://www.laohu8.com/stock/‘

output_file = ‘C:\\try\\StockInfo.txt‘

slist = []

getStockList(slist, stock_list_url)

getStockInfo(slist, stock_info_url, output_file)

main()

20200222200000508757.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值