search
HomeBackend DevelopmentPython TutorialPython制作简单的网页爬虫

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
我们查看该网页的源码可以发现所有的城市列表都是以

,因此,我们可以封装一个函数来通过使用正则表达式获取我们想要的数据,示例代码如下所示:
复制代码 代码如下:
def  ShowCity():
    html=requests.get("http://www.tianqihoubao.com/weather/province.aspx?id=420000")
    citys= re.findall('
', html.text,re.S)
    for city in citys:
        print city
抓取的结果如下所示:
 1 top/anlu.html" title="安陆历史天气查询
 2 top/badong.html" title="巴东历史天气查询
 3 top/baokang.html" title="保康历史天气查询
 4 top/caidian.html" title="蔡甸历史天气查询
 5 top/changyang.html" title="长阳历史天气查询
 6 top/chibi.html" title="赤壁历史天气查询
 7 top/chongyang.html" title="崇阳历史天气查询
 8 top/dawu.html" title="大悟历史天气查询
 9 top/daye.html" title="大冶历史天气查询
10 top/danjiangkou.html" title="丹江口历史天气查询
11 top/dangyang.html" title="当阳历史天气查询
12 top/ezhou.html" title="鄂州历史天气查询
13 top/enshi.html" title="恩施历史天气查询
14 top/fangxian.html" title="房县历史天气查询
15 top/gongan.html" title="公安历史天气查询
16 top/gucheng.html" title="谷城历史天气查询
17 top/guangshui.html" title="广水历史天气查询
18 top/hanchuan.html" title="汉川历史天气查询
19 top/hanyang.html" title="汉阳历史天气查询
20 top/hefeng.html" title="鹤峰历史天气查询
21 top/hongan.html" title="红安历史天气查询
22 top/honghu.html" title="洪湖历史天气查询
23 top/huangpi.html" title="黄陂历史天气查询
24 top/huanggang.html" title="黄冈历史天气查询
25 top/huangmei.html" title="黄梅历史天气查询
26 top/huangshi.html" title="黄石历史天气查询
27 top/jiayu.html" title="嘉鱼历史天气查询
28 top/jianli.html" title="监利历史天气查询
29 top/jianshi.html" title="建始历史天气查询
30 top/jiangxia.html" title="江夏历史天气查询
31 top/jingshan.html" title="京山历史天气查询
32 top/jingmen.html" title="荆门历史天气查询
33 top/jingzhou.html" title="荆州历史天气查询
34 top/laifeng.html" title="来凤历史天气查询
35 top/laohekou.html" title="老河口历史天气查询
36 top/lichuan.html" title="利川历史天气查询
37 top/lvtian.html" title="罗田历史天气查询
38 top/macheng.html" title="麻城历史天气查询
39 top/nanzhang.html" title="南漳历史天气查询
40 top/qichun.html" title="蕲春历史天气查询
41 top/qianjiang.html" title="潜江历史天气查询
42 top/sanxia.html" title="三峡历史天气查询
43 top/shennongjia.html" title="神农架历史天气查询
44 top/shiyan.html" title="十堰历史天气查询
45 top/shishou.html" title="石首历史天气查询
46 top/songzi.html" title="松滋历史天气查询
47 top/suizhou.html" title="随州历史天气查询
48 top/tianmen.html" title="天门历史天气查询
49 top/hbtongcheng.html" title="通城历史天气查询
50 top/tongshan.html" title="通山历史天气查询
51 top/wufeng.html" title="五峰历史天气查询
52 top/wuchang.html" title="武昌历史天气查询
53 top/wuhan.html" title="武汉历史天气查询
54 top/wuxue.html" title="武穴历史天气查询
55 top/hbxishui.html" title="浠水历史天气查询
56 top/xiantao.html" title="仙桃历史天气查询
57 top/xianfeng.html" title="咸丰历史天气查询
58 top/xianning.html" title="咸宁历史天气查询
59 top/xiangyang.html" title="襄阳历史天气查询
60 top/xiaogan.html" title="孝感历史天气查询
61 top/hbxinzhou.html" title="新洲历史天气查询
62 top/xingshan.html" title="兴山历史天气查询
63 top/xuanen.html" title="宣恩历史天气查询
64 top/hbyangxin.html" title="阳新历史天气查询
65 top/yiling.html" title="夷陵历史天气查询
66 top/yichang.html" title="宜昌历史天气查询
67 top/yicheng.html" title="宜城历史天气查询
68 top/yidu.html" title="宜都历史天气查询
69 top/yingcheng.html" title="应城历史天气查询
70 top/hbyingshan.html" title="英山历史天气查询
71 top/yuanan.html" title="远安历史天气查询
72 top/yunmeng.html" title="云梦历史天气查询
73 top/yunxi.html" title="郧西历史天气查询
74 top/hbyunxian.html" title="郧县历史天气查询
75 top/zaoyang.html" title="枣阳历史天气查询
76 top/zhijiang.html" title="枝江历史天气查询
77 top/zhongxiang.html" title="钟祥历史天气查询
78 top/zhushan.html" title="竹山历史天气查询
79 top/zhuxi.html" title="竹溪历史天气查询
80 top/zigui.html" title="秭归历史天气查询
81 [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">(.*&#63;)</table>', html.text,re.S).group(1)
 res=re.findall('<tr>(.*&#63;)</tr>', weather,re.S)
 for x in res[2:]:
  w = re.findall('>(.*&#63;)<', 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">(.*&#63;)</table>', html.text,re.S).group(1)
 res=re.findall('<tr>(.*&#63;)</tr>', weather,re.S)
 for x in res[2:]:
  w = re.findall('>(.*&#63;)<', 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&#63;id=420000")
 citys= re.findall('<td style="height: 22px" align="center"><a href="(.*&#63;)">', 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还是挺适合的,毕竟可以通过它写更少的代码去做更多的事情!!!!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft