前言
python以简洁、易学、强大的特点让人们所熟知,其强大的特点就是可以十分自由的调用第三方库,从而使其功能的生态十分强大,下面的内容,也仅只需要理解python的基本知识便可以上手
一、使用步骤
1.引入库
代码如下(示例):
import re
from os.path import isdir, isfile
import requests
from os import mkdir
2.库的介绍
re库:Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式,其使 Python 语言拥有全部的正则表达式功能。
datetime:Python 中的日期不是其自身的数据类型,但是我们可以导入名为 datetime 的模块,把日期视作日期对象进行处理。
requests库: 唯一的一个非转基因的 Python HTTP 库,处理URL资源特别方便。
os库:os 模块提供了非常丰富的方法用来处理文件和目录。
二、代码实例
import re
from os.path import isdir, isfile
import requests
from os import mkdir
# 获取上证、深证和创业板股票的代码和企业名称获取上证、深证和创业板股票的代码和企业名称
def step1(url, headers):
# 一级文件目录
dir1 = r'E:/python期末设计'
if not isdir(dir1):
mkdir(dir1)
# 请求网页
respond = requests.get(url, headers=headers)
respond.encoding = 'utf-8'
# 匹配每个股票
pattern1 = r'<a href="/gupiao/(.*?)">'
every_gupiao = re.findall(pattern1, respond.text)
with open(rf'{dir1}/股票清单.txt', 'a+', encoding='utf-8') as fp:
for gupiao in every_gupiao:
# 获取每个股票的名称和代码
gupiao_text = re.findall(rf'<a href="/gupiao/{gupiao}">(.*?)</a>', respond.text, re.S)[0]
# 去除股票名称和代码之间的括号
text = re.sub(r'(?<!:)[()]', ' ', str(gupiao_text)).rstrip()
# 过滤含有”ST”和“退”字样的股票,并写入文件中
if 'ST' not in str(text) and '*' not in str(text):
fp.write(text+'\n')
# 获取股票代码的网址
Myurl1 = r'https://www.banban.cn/gupiao/list_sh.html'
# 构造浏览器头
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0'}
step1(Myurl1,header )