您的位置:首页 > 编程语言 > Python开发

Python爬虫实战之爬取链家广州房价_01简单的单页爬虫

2017-02-22 15:56 585 查看

思路介绍

爬取链家广州所有小区信息、在售楼盘及所有历史成交记录,对于超过100个页面的信息,采用曲线爬取的方式,先爬每个小区,然后爬每个小区的在售楼盘及成交记录,后期将进行相应更新,进一步研究Cookie的使用、Proxy(代理)的设置、模拟登录、验证码识别等问题。环境基于Python 2.7。

请求

这里我使用的package是urllib和urllib2,这里列一下爬取过程中需要注意的一些问题。

- 模拟浏览器的行为,设置headers。

- Python 2.x中常见的字符编码和解码问题

首先了解一下字节、字符和编码的关系,ASCII、Unicode和UTF-8的关系,ASCII码一共规定了128个字符的编码,Unicode是一个符号集,只规定了符号的二进制代码,没有规定此二进制代码应该如何存储,结果出现Unicode的多种存储方式,即有许多种不同的二进制格式,可以用来表示Unicode。而UTF-8就是目前使用最广的一种Unicode的实现方式。

Python 2.x里有两种类型的字符串类型:字节字符串和Unicode的字符串。Python根据电脑默认的locale设置将字节转换为字符。

# 获取系统默认的编码方式
<<< import sys
<<< print sys.getdefaultencoding()
'ascii'  # windows默认的编码是ascii
# 更改系统的默认编码
<<< import sys
<<< reload(sys)
<<< sys.setdefaultencoding('UTF-8')


# 为什么reload(sys)
# Python运行时首先加载site.py,把setdefaultencoding方法删除了
if hasattr(sys, "setdefaultencoding"):
del sys.setdefaultencoding


# Python源代码默认是ASCII,可以在源文件开头作如下声明
# -*- coding: UTF-8 -*-


# 读取UTF-8编码的文件,可以手工转换从文件中读取的字符串
<<< import codecs
<<< fileObj = codecs.open(<
4000
span class="hljs-string">"someFile", "r", "UTF-8")
# Returns a Unicode string from the UTF-8 bytes in the file
<<< u = fileObj.read()


Python的decode函数和encode函数,decode是将普通字符串按照参数指定编码格式进行解析,然后生成相应的Unicode对象,encode函数是将一个Unicode对象转换为参数中编码格式的普通字符。

<<< s1 = '哈'.decode('utf-8')
u'\u54c8'
<<< s2 = '哈'.decode('utf-8').encode('utf-8')
'\xe5\x93\x88'


解析

这里采用的是BeautifulSoup,采用标准库中的html解析器,配合正则表达式进行解析。

单页爬虫的代码示例

#! python2
# -*- coding: utf-8 -*-
"""crawl module

@Author: padluo
@WeChat: padluo
"""
import random
import re
import urllib2

from bs4 import BeautifulSoup

HDS = [
{
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},
{
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11'},
{
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'},
{
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:34.0) Gecko/20100101 Firefox/34.0'},
{
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/44.0.2403.89 Chrome/44.0.2403.89 Safari/537.36'},
{
'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'},
{
'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'},
{
'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'},
{
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'},
{
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'},
{
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'},
{
'User-Agent': 'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11'},
{
'User-Agent': 'Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11'}
]

def xiaoqu_crawl(db_xq=None,
url_page=u'http://gz.lianjia.com/xiaoqu/pg1rs%E9%87%91%E7%A2%A7%E4%B8%96%E7%BA%AA%E8%8A%B1%E5%9B%AD/'):
"""爬取页面链接中的小区信息

:param db_xq:
:param url_page:
:return:
"""
try:
# 请求
url_page = u'http://gz.lianjia.com/xiaoqu/pg1rs%E9%87%91%E7%A2%A7%E4%B8%96%E7%BA%AA%E8%8A%B1%E5%9B%AD/'
req = urllib2.Request(url_page,
headers=HDS[random.randint(0, len(HDS) - 1)])
source_code = urllib2.urlopen(req, timeout=10).read()
plain_text = source_code.decode('utf-8')
soup = BeautifulSoup(plain_text, 'html.parser')
except (urllib2.HTTPError, urllib2.URLError), e:
print e
exit(-1)
except Exception, e:
print e
exit(-1)
# 解析
xiaoqu_list = soup.find_all('div', attrs={'class': 'info'})
for xq in xiaoqu_list:
info_dict = {}
info_dict.update({u'小区链接': xq.find('a')['href']})
info_dict.update(
{u'小区名称': xq.find('a', attrs={'target': '_blank'}).get_text()})
content = xq.find('div', attrs={
'class': 'houseInfo'}).renderContents().strip().decode('utf-8')
pat = r'<span.*?/span>.*?<a.*?>(.*?)</a>.*?<a.*?>(.*?)</a>'
info = re.match(pat, content, re.S)
if info:
info = info.groups()
info_dict.update({u'90天成交量': info[0]})
info_dict.update({u'正在出租量': info[1]})
content = xq.find('div', attrs={
'class': 'positionInfo'}).renderContents().strip().decode('utf-8')
pat = r'<span.*?span>.*?<a.*?>(.*?)</a>.*?<a.*?>(.*?)</a>.*?/\xa0(.*)'
info = re.match(pat, content, re.S)
if info:
info = info.groups()
info_dict.update({u'大区域': info[0]})
info_dict.update({u'小区域': info[1]})
info_dict.update({u'建成时间': info[2]})
for info_key, info_value in info_dict.items():
print info_key + '->' + info_value

if __name__ == '__main__':
xiaoqu_crawl()


结果如下:

小区链接->http://gz.lianjia.com/xiaoqu/2111103317968/
大区域->黄埔
建成时间->2004年建成
正在出租量->20套正在出租
小区域->区府
小区名称->金碧世纪花园
90天成交量->90天成交11套
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: