Python带你轻松进行网页爬虫
前不久DotNet开源大本营通过为.NET程序员演示如何在.NET下使用C#+HtmlAgilityPack+XPath进行网页数据的抓取,从而为我们展示了HtmlAgilitypack利器的优点和使用技巧,不熟悉的朋友可以去他的园子里看看这篇文章,真的很不错!我本身也是一名.NET程序员,只是个人兴趣和一些实际需求,所以就打算自学Python。在还没有学它的时候就听说用它来进行网页爬虫和自然语言处理非常方便,所以也就尝试了,结果让我真的很满意!这篇博文就当是对我这一阶段的学习总结吧!
1.准备工作:
工欲善其事必先利其器,因此我们有必要在进行Coding前先配置一个适合我们自己的开发环境,我搭建的开发环境是:
操作系统:Ubuntu 14.04 LTS
Python版本:2.7.6
代码编辑器:Sublime Text 3.0 这次的网络爬虫需求背景我打算延续DotNet开源大本营在他的那篇文章中的需求,这里就不再详解。我们只抓取某一省中所有主要城市从2015-11-22到2015-10-24的白天到夜间的所有天气情况。这里以湖北省为例。
2.实战网页爬虫:
2.1.获取城市列表:
首先,我们需要获取到湖北省所有城市的网页,然后进行网页解析。网络地址为:http://www.tianqihoubao.com/weather/province.aspx?id=420000
我们查看该网页的源码可以发现所有的城市列表都是以<td style="height: 22px" align="center"><a href="城市天气链接+城市名称">,因此,我们可以封装一个函数来通过使用正则表达式获取我们想要的数据,示例代码如下所示:
def ShowCity():
html=requests.get("http://www.tianqihoubao.com/weather/province.aspx?id=420000")
citys= re.findall('<td style="height: 22px" align="center"><a href="(.*?)">', html.text,re.S)
for city in citys:
print city
抓取的结果如下所示:
top/anlu.html" title="安陆历史天气查询
top/badong.html" title="巴东历史天气查询
top/baokang.html" title="保康历史天气查询
top/caidian.html" title="蔡甸历史天气查询
top/changyang.html" title="长阳历史天气查询
top/chibi.html" title="赤壁历史天气查询
top/chongyang.html" title="崇阳历史天气查询
top/dawu.html" title="大悟历史天气查询
top/daye.html" title="大冶历史天气查询
top/danjiangkou.html" title="丹江口历史天气查询
top/dangyang.html" title="当阳历史天气查询
top/ezhou.html" title="鄂州历史天气查询
top/enshi.html" title="恩施历史天气查询
top/fangxian.html" title="房县历史天气查询
top/gongan.html" title="公安历史天气查询
top/gucheng.html" title="谷城历史天气查询
top/guangshui.html" title="广水历史天气查询
top/hanchuan.html" title="汉川历史天气查询
top/hanyang.html" title="汉阳历史天气查询
top/hefeng.html" title="鹤峰历史天气查询
top/hongan.html" title="红安历史天气查询
top/honghu.html" title="洪湖历史天气查询
top/huangpi.html" title="黄陂历史天气查询
top/huanggang.html" title="黄冈历史天气查询
top/huangmei.html" title="黄梅历史天气查询
top/huangshi.html" title="黄石历史天气查询
top/jiayu.html" title="嘉鱼历史天气查询
top/jianli.html" title="监利历史天气查询
top/jianshi.html" title="建始历史天气查询
top/jiangxia.html" title="江夏历史天气查询
top/jingshan.html" title="京山历史天气查询
top/jingmen.html" title="荆门历史天气查询
top/jingzhou.html" title="荆州历史天气查询
top/laifeng.html" title="来凤历史天气查询
top/laohekou.html" title="老河口历史天气查询
top/lichuan.html" title="利川历史天气查询
top/lvtian.html" title="罗田历史天气查询
top/macheng.html" title="麻城历史天气查询
top/nanzhang.html" title="南漳历史天气查询
top/qichun.html" title="蕲春历史天气查询
top/qianjiang.html" title="潜江历史天气查询
top/sanxia.html" title="三峡历史天气查询
top/shennongjia.html" title="神农架历史天气查询
top/shiyan.html" title="十堰历史天气查询
top/shishou.html" title="石首历史天气查询
top/songzi.html" title="松滋历史天气查询
top/suizhou.html" title="随州历史天气查询
top/tianmen.html" title="天门历史天气查询
top/hbtongcheng.html" title="通城历史天气查询
top/tongshan.html" title="通山历史天气查询
top/wufeng.html" title="五峰历史天气查询
top/wuchang.html" title="武昌历史天气查询
top/wuhan.html" title="武汉历史天气查询
top/wuxue.html" title="武穴历史天气查询
top/hbxishui.html" title="浠水历史天气查询
top/xiantao.html" title="仙桃历史天气查询
top/xianfeng.html" title="咸丰历史天气查询
top/xianning.html" title="咸宁历史天气查询
top/xiangyang.html" title="襄阳历史天气查询
top/xiaogan.html" title="孝感历史天气查询
top/hbxinzhou.html" title="新洲历史天气查询
top/xingshan.html" title="兴山历史天气查询
top/xuanen.html" title="宣恩历史天气查询
top/hbyangxin.html" title="阳新历史天气查询
top/yiling.html" title="夷陵历史天气查询
top/yichang.html" title="宜昌历史天气查询
top/yicheng.html" title="宜城历史天气查询
top/yidu.html" title="宜都历史天气查询
top/yingcheng.html" title="应城历史天气查询
top/hbyingshan.html" title="英山历史天气查询
top/yuanan.html" title="远安历史天气查询
top/yunmeng.html" title="云梦历史天气查询
top/yunxi.html" title="郧西历史天气查询
top/hbyunxian.html" title="郧县历史天气查询
top/zaoyang.html" title="枣阳历史天气查询
top/zhijiang.html" title="枝江历史天气查询
top/zhongxiang.html" title="钟祥历史天气查询
top/zhushan.html" title="竹山历史天气查询
top/zhuxi.html" title="竹溪历史天气查询
top/zigui.html" title="秭归历史天气查询
[Finished in 15.4s]
2.2.获取对应城市的所有天气信息:
然后我们需要根据抓取到的城市链接去抓取对应城市的天气情况,这里我们再封装一个函数用于显示对应城市的所有天气状况:
def ShowWeather(city):
res =str(city).split('" title="')
print res[1],'(白天-->夜间)'
html=requests.get("http://www.tianqihoubao.com/weather/{0}".format(res[0]))
weather=re.search('<table width="100%" border="0" class="b" cellpadding="1" cellspacing="1">(.*?)</table>', html.text,re.S).group(1)
res=re.findall('<tr>(.*?)</tr>', weather,re.S)
for x in res[2:]:
w = re.findall('>(.*?)<', x,re.S)
for y in w[1:]:
if len(y.strip())<=0:
pass
else:
print y
print '--'*40
这样以来,我们就可以获取到了对应城市的天气情况了!!
完整代码:
#coding:UTF-8
import re
import requests
import sys
reload(sys)
sys.setdefaultencoding('UTF-8') def ShowWeather(city):
res =str(city).split('" title="')
print res[1],'(白天-->夜间)'
html=requests.get("http://www.tianqihoubao.com/weather/{0}".format(res[0]))
weather=re.search('<table width="100%" border="0" class="b" cellpadding="1" cellspacing="1">(.*?)</table>', html.text,re.S).group(1)
res=re.findall('<tr>(.*?)</tr>', weather,re.S)
for x in res[2:]:
w = re.findall('>(.*?)<', x,re.S)
for y in w[1:]:
if len(y.strip())<=0:
pass
else:
print y
print '--'*40
print '\n','*'*40 def ShowCity():
html=requests.get("http://www.tianqihoubao.com/weather/province.aspx?id=420000")
citys= re.findall('<td style="height: 22px" align="center"><a href="(.*?)">', html.text,re.S)
for city in citys:
ShowWeather(city) def main():
ShowCity() if __name__=='__main__':
main()
是的,你没有看错,短短34行代码就可以爬取湖北省所有的主要城市1个月的所有天气情况,是不是很厉害呀!!???不过不要高兴的太早,凡事有利有弊,看看它的运行结果吧:[Finished in 371.8s]
3.知识总结:
3.1.编码问题:
#在ubuntu上,由于编码问题,我们需要在代码的开始位置添加一行注释,告诉Pyhton解释器我们指定的编码格式: #此外,我们还需要设置默认的编码格式,否则Sublime Text会无法识别中文,报告一个错误:“UnicodeEncodeError: 'ascii' codec can't encode characters in position”
#-*-coding:utf8-*-
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
3.2.正则表达式:
导入正则表达式库:import re
匹配任意字符:.
匹配前一个字符0次或无限次:*
匹配前一个字符0次或一次:?
贪心算法:.*
非贪心算法:.*?
匹配数字:(\d+)
常用函数:
re.findall(pattern, string)
re.search(pattern, string)
re.sub(pattern, repl, string)
最后的最后,如果你尝试过运行我贴出来的完整代码,或许你会遇到和我一样的瓶颈,就是运行的速度不够快(尤其像我这种机器配置不是很好的电脑)。在我的机器上运行这段脚本总共花费了 371.8s。我运行过多次,每次都是在350+。因此,如果你的程序不在乎运行速度,那么可能Python还是挺适合的,毕竟可以通过它写更少的代码去做更多的事情!!!!
Python带你轻松进行网页爬虫的更多相关文章
- Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)
原文:http://www.52nlp.cn/python-网页爬虫-文本处理-科学计算-机器学习-数据挖掘 曾经因为NLTK的缘故开始学习Python,之后渐渐成为我工作中的第一辅助脚本语言,虽然开 ...
- 【Python】Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱
本文转载自:https://www.cnblogs.com/colipso/p/4284510.html 好文 mark http://www.52nlp.cn/python-%E7%BD%91%E9 ...
- Python 3实现网页爬虫
1 什么是网页爬虫 网络爬虫( 网页蜘蛛,网络机器人,网页追逐者,自动索引,模拟程序)是一种按照一定的规则自动地抓取互联网信息的程序或者脚本,从互联网上抓取对于我们有价值的信息.Tips:自动提取网页 ...
- Python网页爬虫(一)
很多时候我们想要获得网站的数据,但是网站并没有提供相应的API调用,这时候应该怎么办呢?还有的时候我们需要模拟人的一些行为,例如点击网页上的按钮等,又有什么好的解决方法吗?这些正是python和网页爬 ...
- python 网页爬虫+保存图片+多线程+网络代理
今天,又算是浪费了一天了.python爬虫,之前写过简单的版本,那个时候还不懂原理,现在算是收尾吧. 以前对网页爬虫不了解,感觉非常神奇,但是解开这面面纱,似乎里面的原理并不是很难掌握.首先,明白一个 ...
- Python编写网页爬虫爬取oj上的代码信息
OJ升级,代码可能会丢失. 所以要事先备份. 一開始傻傻的复制粘贴, 后来实在不能忍, 得益于大潇的启示和聪神的原始代码, 网页爬虫走起! 已经有段时间没看Python, 这次网页爬虫的原始代码是 p ...
- Python十分适合用来开发网页爬虫
Python十分适合用来开发网页爬虫,理由如下:1.抓取网页自身的接口比较与其他静态编程语言,如java,c#,c++,python抓取网页文档的接口更简练:比较其他动态脚本语言,如perl,shel ...
- 多线程网页爬虫 python 实现
采用了多线程和锁机制,实现了广度优先算法的网页爬虫. 对于一个网络爬虫,如果要按广度遍历的方式下载,它就是这样干活的: 1.从给定的入口网址把第一个网页下载下来 2.从 ...
- python实现的一个简单的网页爬虫
学习了下python,看了一个简单的网页爬虫:http://www.cnblogs.com/fnng/p/3576154.html 自己实现了一个简单的网页爬虫,获取豆瓣的最新电影信息. 爬虫主要是获 ...
随机推荐
- Learning WCF:Fault Handling
There are two types of Execptions which can be throwed from the WCF service. They are Application ex ...
- Mybatis关系映射
一.一对一关系映射 使用resultType+包装类实现 1.假设问题背景是要求在某一个购物平台的后台程序中添加一个这样的功能:查询某个订单的信息和下该订单的用户信息.首先我们可以知道,一般这样的平台 ...
- 纯css进度条效果
<!--html代码--> <!DOCTYPE html> <html lang="zh"> <head> <meta cha ...
- touch-action属性引起的探索
最近在做微信项目的时候遇到一个奇怪的问题: 常购清单的商品多了以后往上滑没有任何反应,不能滑动.但商城首页又可以往上滑.而且ios没有这个问题,安卓才有这个问题. 起初我以为是因为这2个页面调用接口 ...
- eclipse clean和build作用
由于eclipse的编译是基于时间戳的判断机制的. 因此当你按build all的时候有些eclipse认为时间戳没有改变的类不会被编译. 因此你可以先clean一下再编译.这个时候eclipse ...
- [EXP]Apache Spark - Unauthenticated Command Execution (Metasploit)
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://gith ...
- SpringBoot 遇到 com.google.guava » guava 组件运行异常问题修复方案
环境 Apache Maven : 3.5.4 org.springframework.boot » spring-boot-starter-parent : 2.0.3.RELEASE io.spr ...
- Android的Fragment中的互相通信-桥梁activity
Android的Fragment中的互相通信-桥梁activity 效果图如下: 项目结构图如下: Fragment1: package com.demo.fragmenttongxin; impor ...
- 关于 Nginx 配置 WebSocket 400 问题
今天把项目升级了 asp.net core 到 2.1 的版本,使用了 signalr 的功能,由于阿里云不支持 websocket 协议,所以使用了 nginx 代理方式来解决,后续就报了一个登陆 ...
- 从零开始学 Web 之 Ajax(七)跨域
大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:ht ...