抓取数据不管用什么编程语言几乎都是可以实现了,今天我们需要采集安居客的小区数据,下面我们来看一个python抓取安居客小区数据的程序代码了,希望下文能够对大家有帮助。
某功能需要一套城市所有小区的位置信息数据,一开始是使用的百度地图api来进行关键词搜索,勉强能用,但数据量非常少,还是有大量的社区/小区搜不到。
周末在家上网时发现安居客上直接就有每个城市的小区大全,欣喜若狂,于是就立即写了个爬虫试试。
以下贴代码,python2.7,lxml+request库。
#coding=utf-8 #author : zx #date : 2015/07/27 import requests import MySQLdb import time import string import random from lxml import etree #ua头信息 get时可以随机使用 headers = [ { "User-Agent":"Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"}, { "User-Agent":"Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)"}, { "User-Agent":"Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+"}, { "User-Agent":"Mozilla/5.0 (Linux; Android 4.4.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36"} ] #城市入口页面 #我只抓的青岛本地 #其它城市或全国城市可通过这个页面抓取城市列表http://m.anjuke.com/cityList url = 'http://m.anjuke.com/qd/xiaoqu/' req = requests.get(url) cookie = req.cookies.get_dict() #链接数据库 conn = MySQLdb.connect('localhost', '*****', '******', '***', charset='utf8') cursor = conn.cursor() sql = "insert into xiaoqu (name, lat, lng, address, district) values (%s, %s, %s, %s, %s)" sql_v = [] page = etree.HTML(req.text) districtHTML = page.xpath(u"//div[@class='listcont cont_hei']")[0] #采集目标城市的各行政区域url #当然如果不想区分行政区可以直接抓“全部” 即上面url中的所有小区及分页 districtUrl = {} i = 0 for a in districtHTML: if i==0: i = 1 continue districtUrl[a.text] = a.get('href') #开始采集 total_all = 0 for k,u in districtUrl.items(): p = 1 #分页 while True: header_i = random.randint(0, len(headers)-1) url_p = u.rstrip('/') + '-p' + str(p) r = requests.get(url_p, cookies=cookie, headers=headers[header_i]) page = etree.HTML(r.text) #这里转换大小写要按情况... communitysUrlDiv = page.xpath(u"//div[@class='items']")[0] total = len(communitysUrlDiv) i = 0 for a in communitysUrlDiv: i+=1 r = requests.get(a.get('href'), cookies=cookie, headers=headers[header_i]) #抓取时发现有少量404页会直接导致程序报错退出- -! #唉 说明代码写的还不够健壮啊 #加了if判断和try, 错误时可以跳过或做一些简单处理和调试... if r.status_code == 404: continue page = etree.HTML(r.text) try: name = page.xpath(u"//h1[@class='f1']")[0].text except: print a.get('href') print r.text raw_input() #有少量小区未设置经纬度信息 #只能得到它的地址了 try: latlng = page.xpath(u"//a[@class='comm_map']")[0] lat = latlng.get('lat') lng = latlng.get('lng') address = latlng.get('address') except: lat = '' lng = '' address = page.xpath(u"//span[@class='rightArea']/em")[0].text sql_v.append((name, lat, lng, address, k)) print "\r\r\r", print u"正在下载 %s 的数据,第 %d 页,共 %d 条,当前:".encode('gbk') %(k.encode('gbk'),p, total) + string.rjust(str(i),3).encode('gbk'), time.sleep(0.5) #每次抓取停顿 #执行插入数据库 cursor.executemany(sql, sql_v) sql_v = [] time.sleep(5) #每页完成后停顿 total_all += total print '' print u"成功入库 %d 条数据,总数 %d".encode('gbk') % (total, total_all) if total < 500: break else: p += 1 #及时关闭数据库 做个好孩子 任务完成~ cursor.close() conn.close() print u'所有数据采集完成! 共 %d 条数据'.encode('gbk') % (total_all) raw_input()
注释我觉得已经写的很详细了,在cmd中显示,字符串当然要转一下码。
以下是运行状态和得到的数据截图。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.