python爬虫教程代码示例经典例子菜鸟怎么学

本文适合零基础学习爬虫的读者,作者通过一个股票数据爬虫实例,介绍了Python2.7中涉及的库如urllib, requests, BeautifulSoup等的使用。文中讲解了如何获取网页、处理网页乱码、解析网页数据,以及数据的读写操作,包括CSV和MySQL。案例中,作者爬取了上海链家网的房产数据,强调了在实际爬取中可能遇到的反爬虫策略和解决办法。" 135903435,7337247,深度学习框架PyTorch详解:从核心概念到最佳实践,"['人工智能', '深度学习', 'PyTorch', '自动求导', '张量']
摘要由CSDN通过智能技术生成

实例3–股票数据定向爬虫

程序结构如下:

1.先从网站中获取股票代号列表(requests库,re库)

2.遍历每一只股票,从股票信息网站中获得详细信息

3.使用字典的数据结构,写入文本文件中

 

更多的内容学习 点我

以下为代码:

复制代码

 1 # 股票数据定向爬虫
 2 """
 3 Created on Thu Oct 12 16:12:48 2017
 4 
 5 @author: DONG LONG RUI
 6 """
 7 import requests
 8 from bs4 import BeautifulSoup
 9 import re
10 #import traceback
11 
12 def getHTMLText(url,code='utf-8'):#参数code缺省值为‘utf-8’(编码方式)
13     try:
14         r=requests.get(url,timeout=30)
15         r.raise_for_status()
16         #r.encoding=r.apparent_encoding
17         r.encoding=code
18         return r.text
19     except:
20         return ''
21     
22 def getStockList(lst,stockURL):
23     html=getHTMLText(stockURL,'GB2312')
24     soup=BeautifulSoup(html,'html.parser')
25     a=soup.find_all('a')
26     for i in a:
27         try:
28             href=i.attrs['href']
29             lst.append(re.findall(r'[s][hz]d{6}',href)[0])
30         except:
31             continue
32     
33 def getStockInfo(lst,stockURL,fpath):
34     count=0#
35     for stock in lst:
36         url=stockURL+stock+'.html'
37         html=getHTMLText(url)
38         try:
39             if html=='':
40                 continue
41             infoDict={}
42             soup=BeautifulSoup(html,'html.parser')
43             stockInfo=soup.find('div',attrs={'class':'stock-bets'})
44             
45             name=stockInfo.find_all(attrs={'class':'bets-name'})[0]
46             infoDict.update({'股票名称':name.text.split()[0]})#用空格分开,得到股票名称
47             
48             keyList=stockInfo.find_all('dt')
49             valueList=stockInfo.find_all('dd')
50             for i in range(len(keyList)):
51                 key=keyList[i].text
52                 val=valueList[i].text
53                 infoDict[key]=val
54             
55             with open(fpath,'a',encoding='UTF-8') as f:
56                 f.write(str(infoDict)+'n')
57                 count=count+1#
58                 print('r当前进度:{:.2f}%'.format(count*100/len(lst)),end='')#动态显示进度,‘r’实现光标移动,即为不换行的效果
59         except:
60             count=count+1
61             print('r当前进度:{:.2f}%'.format(count*100/len(lst)),end='')#动态显示进度,‘r’实现光标移动,即为不换行的效果
62             #traceb
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值