有朋友工作需要从58同城上爬取部分数据,他之前用的免费版的"火车头"功能比较少,不能达到预期效果,所以请我帮忙.
刚好最近正在自学python,听说python实现网络爬虫比较简单,就在工作之余研究了一下.
关于XPATH,请移步(有中文文档,很赞):http://zvon.org/xxl/XPathTutorial/General/examples.html
好了,在知识储备差不多的情况下,开始着手爬数据
2.因为lxml在解析复杂html时会报错,所以建议安装BeautifulSoup-3.2.1,下载链接https://pypi.python.org/packages/source/B/BeautifulSoup/BeautifulSoup-3.2.1.tar.gz,安装方法烦请百度
刚好最近正在自学python,听说python实现网络爬虫比较简单,就在工作之余研究了一下.
关于python基础学习,请移步(廖雪峰的官方网站):http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/
关于python实现网络爬虫,也是在某大侠(请叫我汪海)的博客专栏中学习了将近一天:请移步:http://blog.csdn.net/column/details/why-bug.html关于XPATH,请移步(有中文文档,很赞):http://zvon.org/xxl/XPathTutorial/General/examples.html
好了,在知识储备差不多的情况下,开始着手爬数据
先决条件:
1.安装python2.因为lxml在解析复杂html时会报错,所以建议安装BeautifulSoup-3.2.1,下载链接https://pypi.python.org/packages/source/B/BeautifulSoup/BeautifulSoup-3.2.1.tar.gz,安装方法烦请百度
接下来就是重头戏了,我的思路是请求58同城,获取响应并读取响应信息,将响应信息解析为顶级元素,然后使用XPATH获取想要的数据结果,最后打印输出,因为业务逻辑比较简单,故直接上代码:
#coding=utf-8
#从58同城爬取数据
#Created on 2015年4月9日
#author: windbeside
import urllib2
from lxml import etree
from lxml.html import soupparser
def test():
#获取请求对象
req = urllib2.Request('http://zz.58.com/ershoufang/pn1/?qq-pf-to=pcqq.group&PGTID=14285900569950.5156099369318879&ClickID=1')
try:
#得到服务器响应
resp = urllib2.urlopen(req)
#将响应的页面读取到一个字符串中
html = resp.read()
#关闭流
resp.close()
#使用soupparser将字符串格式的html解析为顶级元素对象
doc = soupparser.fromstring(html)
#获取指定行的集合
row = doc.xpath(u"body/div[@id='category']/div[@id='main']/div[@id='infolist']/table[@class='tbimg']/tr")
i = 0
#指定元素对应的XPATH
huxingPath = "td[@class='t']/div[@class='qj-listright btall']/span[@class='showroom']"
shoujiaPath = "td[@class='t']/div[@class='qj-listright btall']/b[@class='pri']"
weizhiPath = "td[@class='t']/div[@class='qj-listleft']/i[@class='clear']"
fabushijianPath = "td[@class='t']/div[@class='qj-listleft']/span[@class='qj-listjjr']"
#循环遍历每一行
for r in row:
#户型信息(转码,去空)
huxing = r.find(huxingPath).text_content().encode('utf-8').strip()
#售价信息
shoujia = r.find(shoujiaPath).text
#位置信息(先获取其之后的元素,然后调用getprevious()方法获取位置元素,转码,去空)
weizhi = r.find(weizhiPath).getprevious().text.encode('utf-8').strip()
#发布信息(转码,去空)
fabushijian = ('').join(r.find(fabushijianPath).xpath('text()')).encode('utf-8').strip()
i += 1
#r = r.text_content().encode('utf-8')
print '抓取的第%d 行记录中户型为%s'%(i, huxing)
print '抓取的第%d 行记录中售价为%s'%(i, shoujia)
print '抓取的第%d 行记录中位置为%s'%(i, weizhi)
print '抓取的第%d 行记录中发布时间为%s'%(i, fabushijian)
except urllib2.URLError, e:
if hasattr(e, 'code'):
print 'exception code:%s'%(e.code)
elif hasattr(e, 'reason'):
print 'exception reason:%s'%(e.reason)
else:
raise
test()