技术标签: python Python网络爬虫之制作股票数据定向爬虫 以及爬取的优化 可以显示进 网络爬虫python
候选网站:
新浪股票:http://finance.sina.com.cn/stock/
百度股票:https://gupiao.baidu.com/stock/
选取原则:
F12,查看源代码,即可查看。
新浪股票,使用JS制作。脚本生成的数据。
百度股票可以在HTML中查询到!
http://quote.eastmoney.com/stocklist.html
这个地址可以查询股票详细列表!
程序思路:
1. 获取股票列表
2. 根据列表信息到百度获取个股信息2,根据列表信息到百度获取个股信息
3. 将结果存储
考虑用字典作为数据容器进行存储!
火狐浏览器可以查看源代码,蓝色的IE浏览器就会出现乱码:
火狐的:
因为a标签,太多所以正则表达式匹配比较困难。
可用try except来解决!
[s]:表示s。[hz]:表示h z。后面是随意6个数。
SH:
SZ:
优化:
优化就是将编码直接给代码,另外一个就是显示进度。
下面就是代码部分啦:
最初的代码:(真长)
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"
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div', attrs={'class':'stock-bets'})
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valurList[i].text
infoDict[key] = val
with open(fpath, 'a', encoding='utf-8') as f:
f.write(str(infoDict) + '\n')
except:
traceback.print_exc()
continue
def main():
stock_list_url = 'https://quote.eastmoney.com/stocklist.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D:\234.txt'
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()
代码执行结果;
优化后的代码:
import requests
from bs4 import BeautifulSoup
import traceback
import re
def getHTMLText(url,code='utf-8'):#默认的是utf-8
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = code#直接赋值
return r.text
except:
return ""
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])
except:
continue
def getStockInfo(lst, stockURL, fpath):
count = 0
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div', attrs={'class':'stock-bets'})
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valurList[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:
count = count +1
print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end=' ')
traceback.print_exc()
continue
def main():
stock_list_url = 'https://quote.eastmoney.com/stocklist.html'
stock_info_url = 'https://gupiao.baidu.com/stock/'
output_file = 'D:\234.txt'
slist = []
getStockList(slist, stock_list_url)
getStockInfo(slist, stock_info_url, output_file)
main()
提前给出了编码方式以及可以显示进度条的代码
给出编码方式的代码:
def getHTMLText(url,code='utf-8'):#默认的是utf-8
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = code#直接赋值
return r.text
except:
return ""
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])
except:
continue
照片:
(如果不是utf-8,就要提前给替换掉!)
可以显示进度条的代码
def getStockInfo(lst, stockURL, fpath):
count = 0
for stock in lst:
url = stockURL + stock + ".html"
html = getHTMLText(url)
try:
if html == "":
continue
infoDict = {}
soup = BeautifulSoup(html, 'html.parser')
stockInfo = soup.find('div', attrs={'class':'stock-bets'})
name = stockInfo.find_all(attrs={'class':'bets-name'})[0]
infoDict.update({'股票名称':name.text.split()[0]})
keyList = stockInfo.find_all('dt')
valueList = stockInfo.find_all('dd')
for i in range(len(keyList)):
key = keyList[i].text
val = valurList[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:
count = count +1
print('\r当前速度:{:.2f}%'.format(count*100/len(lst)),end=' ')
traceback.print_exc()
continue
照片:
不过,显示进度在IDLE那里不可以显示。
但是最后我也没成功有文件生成以及显示进度条,算啦。先去吃饭啦~
由于Android 4.0 之后不能在主线程中请求HTTP请求,所以请求必须放在子线程中进行。Http请求方式Get与Post的简介 先来了解Http协议:Http(HyperText Transfer Protocol超文本传输协议)是一个设计来使客户端和顺利进行通讯的协议。HTTP在客户端和服务器之间以request-response protocol(请求-回复协议)工作。简单来说呢,Get与Post就是基于http协议的网络数据交互方式。......_uniapp能直接访问post请求吗
开发物联网应用时,选择合适的程序开发语言和选择合适的硬件平台一样重要。本文将会列出一些你可能会用到的语言,并有适当的应用场景分析;不过在你继续阅读之前,不妨试着来预测一下下面会出现哪些语言。 物联网现在是个大热门相信谁也不能否认,各种开发项目正如雨后春笋般出现在地球村的各个角落。不断出现的新硬件平台让工程师能够越来越容易地打造新的嵌入式设备。当你选择了其中的某一个硬件平台之后,你还需要为_go-iot
大一下本期数据结构数据结构题目集两个有序链表序列的交集 (20 分)已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。输入格式:输入分两行,分别在每行给出由若干个正整数构成的非降序序列,用−1表示序列的结尾(−1不属于这个序列)。数字用空格间隔。输出格式:在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出NULL。..._7-3 两个有序链表序列的交集
问题一: mfc单文档分割窗口出现了这个错误解决办法: 在mainfrm.cpp中包含“***view.h”文件前包含“***doc.h”文件问题二: 分割窗口的时候运行程序显示“创建文档失败”。原因:在分割后的模块中插入的对话框基类是CdilogEx。解决方案:重建工程插入基类是CFormView的对话框后正常。..._warning c4183
TCGA的关键数字:图片来源《细胞》由美国政府发起的癌症和肿瘤基因图谱(Cancer Genome Atlas,TCGA)计划于2006年联合启动,目前已经收录了来自1万多例病人的33种癌症的数据,2.5PB的数据量。全世界无数顶尖肿瘤学家经过10多年的辛苦工作,于近期公布了TCGA研究的收官之作:“Pan-Cancer Atlas”泛癌症图谱。这些研究精华共发表了27篇相关论文,..._27篇cell收官之作解析
【Linux学习】Linux必备命令(一)–之touch命令详解。_linux touch
报错错误原因:没有@mapper注解解决方法:1.在启动类在spring boot Application主文件下加上@MapperScan("mapper的包名")例如@MapperScan("com.jt.mapper")2.在每个mapp类中加@mapper注解
基础入门-系统及数据库等注:数据库漏洞比较少,一般都是弱口令漏洞。第三方类似于pc安装的第三方软件,也可以作为我们的突破口。操作系统层面识别操作系统常见方法:若有url则可以通过windows中url不区分大小写,而linux是区分大小写或者可通过ping,ip地址的ttl来通过不同的ttl,来判断不同的操作系统。在者可以通过nmap,命令为nmap -O 47.75.212.155也可以判断操作系统。不同的操作系统,方法不同。MS17010,是系统远程代码执行。这个漏洞不需要前提条_如何启动一个mysql服务(版本:5.5.23),监听3306端口
建立Voronoi图方法和步骤实验采用的是Delaunay三角剖分算法。主要是指生成Voronoi图时,先生成其对偶元Delaunay三角网,再找出三角网每一三角形的外接圆圆心,最后连接相邻三角形的外接圆圆心,形成以每一三角形顶点为生成元的多边形网。如下图所示。建立Voronoi图算法的关键是对离散数据点合理地连成三角网,即构建Delaunay三角网。 建立Vorono_线 vonori图
mysql group by 版本问题今天服务器过期了,服务器重启后,之前的mysql设置mode无效报错信息如下:Error querying database. Cause: java.sql.SQLSyntaxErrorException:"\n### Error querying database. Cause: java.sql.SQLSyntaxErrorException: Expression #24 of SELECT list is not in GROUP BY clause
一、gotoGo语言的goto语句可以无条件地转移到程序中指定的行。goto语句通常与条件语句配合使用。可用来实现条件转移,跳出循环体等功能。在Go程序设计中一般不主张使用gota语句,以免造成程序流程的混乱,使理解和调试程序都产生困难。二、goto入门//goto入门练习package mainimport ( "fmt" )func main(){ var a1 int = 20 fmt.Println("ko1") fmt.Println("ko2") if a1 &g_go gota
WinSCP为了开发生产中更方便地在linux虚拟机->windows->开发板中传输文件,给大家介绍一个方便的文件互传小工具。WinSCP特点图形用户界面多语言与 Windows 完美集成(拖拽, URL, 快捷方式)支持所有常用文件操作支持基于 SSH-1、SSH-2 的 SFTP 和 SCP 协议支持批处理脚本和命令行方式多种半自动、自动的目录同步方式内置文本编辑器支持 SSH 密码、键盘交互、公钥和 Kerberos(GSS) 验证通过与 Pageant(PuT_winscp连接开发板教程