py爬虫4

第一步从东方财富网获取股票列表
第二步根据股票列表逐个到百度股票获取信息
第三步将所有文件打印到列表中

import requests
from bs4 import BeautifulSoup
import traceback
import re

def getHTMLText(url):
return “” /获取链接

def getStockList(lst, stockURL):
return “” /获取股票列表的网站

def getStockInfo(lst, stockURL, fpath):
return “” /储存的文件路径

def main(): /获取股票连接的主体
stock_list_url = ‘http://quote.eastmoney.com/stock_list.html’
stock_info_url = ‘http://stockpage.10jqka.com.cn/’
outout_file = ‘C://Users/zsnzd/Downloads/BaiduStickInfo.txt’
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stick_info_url, output_file)

main()

import requests
from bs4 import BeautifulSoup
import traceback
import re

def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return""

def getStockList(lst, stockURL):
html = getHTMLText(stockURL)
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])
except:
continue

def getStockInfo(lst, stockURL, fpath):
for stock in lst:
url = stockURL + stock
html = getHTMLText(url)
try:
if html == “”: /出现空
continue
infoDict = {} / 定义字典存储信息
soup = BeautifulSoup(html, ‘html.parser’) /解析网页用soup

        stockInfo = soupfind('div', attrs={'class':'m_content'})
         /查找股票编码信息

        name = stockInfo.find_all(attrs={'class':'m_header'})[0]
        infoDict.update({'股票名称':name.text.split()[0]})
        keyList = stockInfo.find_all('tr')
        valueList = stockInfo.find_all('td')
        for i in range(len(keyList)):/打印到列表
            key = keyList[i].text
            infoDick[key] = val

        with open(fpath, 'a', encoding='utf-8') as f:
            f.write(str(infoDict) + '\n')

    except:
        traceback.print_exc()
        continue\获得异常
return ""

def main():
stock_list_url = ‘http://quote.eastmoney.com/stock_list.html’
stock_info_url = ‘http://stockpage.10jqka.com.cn/’
outout_file = ‘C://Users/zsnzd/Downloads/BaiduStickInfo.txt’
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stick_info_url, output_file)

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值