爱帮网单个网址:http://www.aibang.com/detail/17881112-420243957
截图:
本文采集该页面的标题和2个电话号码,具体的python代码:
# -*- coding: UTF-8 -*- ''' Created on 2012-6-9 @author: crazyant ''' #导入urllib2库,用于获取网页 import urllib2 #使用开源库Webscraping库的xpath模块 from Webscraping import xpath,common #首先,发送请求到爱帮网的一个页面,该页面含有地址 req = urllib2.Request('http://www.aibang.com/detail/17881112-420243957') #获得响应 reponse = urllib2.urlopen(req) #将响应的内容存入html变量 html = reponse.read() #以下抓取页面的标题 title = xpath.search(html, '//div[@class="ppc_title"]/h1[1]') print '标题:' #这里要输出中文,因此采用common的to_unicode输出 print common.to_unicode(title[0], 'utf-8') #使用xpath得到电话号码的节点 tel = xpath.search(html, '//dl[@class="detail_list"]/dd[@class="fb"]') #使用正则拆分数字 import re m = re.search(r'([\d-]+)\s([\d-]+)', tel[0]) #如果匹配,输出两个单个电话号码 print '电话号:' if m is not None: for t in m.groups(): print t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# -*- coding: UTF-8 -*-
''
'
Created on 2012-6-9
@author: crazyant
'
''
#导入urllib2库,用于获取网页
import
urllib2
#使用开源库Webscraping库的xpath模块
from
Webscraping
import
xpath
,
common
#首先,发送请求到爱帮网的一个页面,该页面含有地址
req
=
urllib2
.
Request
(
'http://www.aibang.com/detail/17881112-420243957'
)
#获得响应
reponse
=
urllib2
.
urlopen
(
req
)
#将响应的内容存入html变量
html
=
reponse
.
read
(
)
#以下抓取页面的标题
title
=
xpath
.
search
(
html
,
'//div[@class="ppc_title"]/h1[1]'
)
print
'标题:'
#这里要输出中文,因此采用common的to_unicode输出
print
common
.
to_unicode
(
title
[
0
]
,
'utf-8'
)
#使用xpath得到电话号码的节点
tel
=
xpath
.
search
(
html
,
'//dl[@class="detail_list"]/dd[@class="fb"]'
)
#使用正则拆分数字
import
re
m
=
re
.
search
(
r
'([\d-]+)\s([\d-]+)'
,
tel
[
0
]
)
#如果匹配,输出两个单个电话号码
print
'电话号:'
if
m
is
not
None
:
for
t
in
m
.
groups
(
)
:
print
t
|
运行结果:
标题:
坊上人清真饭庄(高新店)
电话号:
029-88222668
029-88226458
其中主要用到了以下模块:
- xpath:用于使用路径的方法找到节点
- re:正则表达式模块,用于拆分电话号码(其实字符串函数也可以)
- urllib2:用于请求指定URL的页面内容,存于字符串然后分析
- webscraping 库的common模块:用于将获取到得中文文本转成unicode编码,这样才能够输出