目录
1. Python安装与IDE安装
当前使用的Python版本为:3.6.2,使用的IDE为PyCharm
Pythona安装教程:https://blog.csdn.net/nmjuzi/article/details/79075736
PyCharm安装与使用:https://blog.csdn.net/yctjin/article/details/70307933?locationNum=11&fps=1
PyCharm激活:https://blog.csdn.net/u014044812/article/details/78727496
2. Python获取网页数据
2.1 创建工程
安装好PyCharm后,打开软件,点击Create New Project 创建新的工程项目,默认选中为 Pure Python,然后在Location一栏选择路径输入项目名称。
创建成功后进入PyCharm后,选中项目 右键 -> New -> Python Package 创建包,方便管理。
创建包之后,选中刚创建的包 右键 -> New -> Python File 创建Python文件,代码便是在此编写。
2.2 获取Html文本
"""
我是注释,当前想要实现的功能是,获取所有股票的名字以及代码
"""
import urllib.request
# 获取网址url 对应的Html文本信息 的函数
def downHtml(url):
html = urllib.request.urlopen(url).read()
return html
# 主函数
if __name__ == '__main__':
# 打印网址对应 的html文本信息
print(downHtml("http://quote.eastmoney.com/stocklist.html#sz"))
运行程序,选中创建的 .py 文件,然后右键 run 项目结构以及运行方式如下图
成功运行后,就可以在控制台上看到打印的内容。
2.3 Html文本解析
前面获取的是网址对应的所有Html文本,而我只需要股票代码和名字,所以需要对Html进行解析。
在网页解析前,需要知道获取到的Html文本格式。
首先打开网址:http://quote.eastmoney.com/stocklist.html#sz
然后在网页空白处,右键点击 “检查元素" 或 ”检查” 或直接按 F12 等等,可以查看Html信息
格式如下图:
对网页解析的方法有正则表达式,Beautiful Soup,Lxml等等,我在此使用比较方便的Beautiful Soup
Beautiful Soup 安装
打开命令行,输入
pip install beautifulsoup4
Beautiful Soup 使用
每行代码的作用都写在注释里了
def parseHtml(html):
# 设置编码格式GBK 避免控制台打印乱码
soup = BeautifulSoup(html, from_encoding='gbk')
# 得到 <div id="quotesearch"> 标签对应的内容
div = soup.find('div', attrs={'id': 'quotesearch'})
# 得到 <div> 标签下的所有 <li>标签内容
lis = div.find_all('li')
# 定义一个存股票名字的 列表
names = []
# 循环遍历 <li>标签
for li in lis:
# 此时得到的是<a>标签的所有内容
# 示例:<a href="http://quote.eastmoney.com/sh201000.html" target="_blank">R003(201000)</a>,
a = li.find('a', attrs={'target': '_blank'})
# 此时才是得到<a> 标签内 对应的值 即股票名字及其代码 示例:'广州发展(600098)'
name = a.text
# 将名字 添加进names列表中
names.append(name)
return names
然后在主函数中调用前面编写的方法。
# 主函数
if __name__ == '__main__':
# 打印网址对应 的html文本信息
html = downHtml("http://quote.eastmoney.com/stocklist.html#sz")
stockName = parseHtml(html)
print(stockName)
运行,查看打印信息
股票名字及其代码是得到了,但是出现了错误信息
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.
大致意思是,BeautifulSoup 未指定解析器,通常使用“html.parser”解析器。所以修改BeautifulSoup 的使用代码即可。
# 设置编码格式GBK 避免控制台打印乱码
soup = BeautifulSoup(html, 'html.parser', from_encoding='gbk')
3. 存储抓取的网页数据
前面已经获取到了股票得名字列表,现在只需要创建文件,并将数据写入文件中即可保存,代码如下
def saveData(names):
# 存储数据得文件夹
file_dir = 'D:\\python\\study20180829'
# 存储数据得文件名
file_name = 'stockName.txt'
# 拼接一个完整得路径
file = os.path.join(file_dir, file_name)
# 如果此文件夹路径不存在,就创建文件夹
if not os.path.exists(file_dir):
os.makedirs(file_dir)
# 打开一个文件,如果不存在 则创建该文件
with open(file, 'w') as fileObj:
# 将名字列表 names 拼接为一个字符串 并以 换行符'\n' 分隔
fileObj.write('\n'.join(names))
运行然后查看结果:
本文完整得代码如下:
"""
我是注释,当前想要实现的功能是,获取所有股票的名字以及代码
"""
import urllib.request
import os
from bs4 import BeautifulSoup
# 获取网址url 对应的Html文本信息 的函数
def downHtml(url):
try:
html = urllib.request.urlopen(url).read()
except urllib.request.URLError as e:
print(e.reason)
return html
def parseHtml(html):
# 设置编码格式GBK 避免控制台打印乱码
soup = BeautifulSoup(html, 'html.parser', from_encoding='gbk')
# 得到 <div id="quotesearch"> 标签对应的内容
div = soup.find('div', attrs={'id': 'quotesearch'})
# 得到 <div> 标签下的所有 <li>标签内容
lis = div.find_all('li')
# 定义一个存股票名字的 列表
names = []
# 循环遍历 <li>标签
for li in lis:
# 此时得到的是<a>标签的所有内容
# 示例:<a href="http://quote.eastmoney.com/sh201000.html" target="_blank">R003(201000)</a>,
a = li.find('a', attrs={'target': '_blank'})
# 此时才是得到<a> 标签内 对应的值 即股票名字及其代码 示例:'广州发展(600098)'
name = a.text
# 将名字 添加进names列表中
names.append(name)
return names
# 保存数据
def saveData(names):
# 存储数据得文件夹
file_dir = 'D:\\python\\study20180829'
# 存储数据得文件名
file_name = 'stockName.txt'
# 拼接一个完整得路径
file = os.path.join(file_dir, file_name)
# 如果此文件夹路径不存在,就创建文件夹
if not os.path.exists(file_dir):
os.makedirs(file_dir)
# 打开一个文件,如果不存在 则创建该文件
with open(file, 'w') as fileObj:
# 将名字列表 names 拼接为一个字符串 并以 换行符'\n' 分隔
fileObj.write('\n'.join(names))
# 主函数
if __name__ == '__main__':
# 打印网址对应 的html文本信息
html = downHtml("http://quote.eastmoney.com/stocklist.html#sz")
stockName = parseHtml(html)
saveData(stockName)