python 安居客 爬虫_Python爬虫安居客房价信息(并利用百度地图API查询坐标)
完整代碼如下:
#-*- coding:utf-8 -*-#這個爬蟲是獲取安居客小區數據(需要header)
importrequestsfrom bs4 importBeautifulSoupfrom urllib2 importurlopen, quoteimportjsonimportsysimporttimefrom xpinyin importPinyin #導入拼音模塊
reload(sys)
sys.setdefaultencoding("utf-8")classajkxq: #創建一個類,類中有兩個函數,分別是獲取小區信息的getInfo()和得到小區名稱后查詢其經緯度的getlnglat(),其中getInfo()會調用getlnglat()函數
defgetlnglat(self,address):"""根據傳入地名參數獲取經緯度"""url= 'http://api.map.baidu.com/geocoder/v2/'output= 'json' #輸出結果可以是json也可以是其他類型ak= '你自己的密鑰'add= quote(str(address))#有時候quote會出錯KeyError,要先把quote里面轉成字符串類型
uri = url + '?' + 'address=' + add + '&output=' + output + '&ak=' +ak
#構建百度地圖API查詢需要的uri,uri與URL的區別見:https://www.zhihu.com/question/21950864
#下面這塊代碼是為了防止因為請求次數過多而產生的錯誤:urllib2.URLError:
#如果出現該錯誤,就讓程序暫停10秒(time.sleep(10)),繼續重新獲取該小區的坐標。
#timeout=30是防止因為網絡原因出現延遲錯誤
maxNum=5
for tries inrange(maxNum):try:
req= urlopen(uri,timeout=30)#設置timeout30秒,防止百度屏蔽,如果被屏蔽就等30秒
except:if tries < (maxNum - 1):
time.sleep(10)continue
else:print("Has tried %d times, all failed!", maxNum)breakres=req.read().decode()
temp=json.loads(res)
lat= temp['result']['location']['lat']
lng= temp['result']['location']['lng']returnlat, lng
#獲取小區信息的函數defgetInfo(self, page, fh, city, citypy):
url= 'https://'+citypy+'.anjuke.com/community/p' + str(page)+'/'headers={ #由于安居客網站的反爬蟲,這里必須要設置header'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Language': 'zh-CN,zh;q=0.8','Referer': 'https: // wuhan.anjuke.com / sale /?from=navigation','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
response= requests.get(url, headers=headers,timeout=30)
#以下是解析網頁的過程
bs= BeautifulSoup(response.text, 'html.parser')lis= bs.find_all('div', class_='li-itemmod')for li inlis:
infos= li.find_all('div', class_='li-info')for info ininfos:
titles= info.find_all('h3')for title intitles:
strTitle=title.get_text()printcity,page,strTitleli_sides= li.find_all('div', class_='li-side')
strPrice= '暫無均價'
for li_side inli_sides:
ps= li_side.find_all('p')for p inps:
strongs=p.find_all('strong')for price instrongs:
strPrice=price.get_text()printstrPrice
address= city + strTitle #在前面加上城市變量,限定查詢城市
try:
lat, lng=test.getlnglat(address)printlat, lng
fh.write(city.strip()+','+strTitle.strip() + ',' + str(lat).strip() + ',' + str(lng).strip() +','+ strPrice.strip() + '\n')#strip()是去掉每行后面的換行符,只有str類型才能用strip()
except KeyError: #處理未知異常
print("Get AError")if __name__ == '__main__':print "開始爬數據,請稍等..."start_time=time.time()
tup1=[ #設置元組,循環取元組中的元素
'廣州','深圳', '佛山', '東莞', '珠海', '中山', '惠州', '肇慶', '江門', '清遠', '汕頭','梅州', '河源','揭陽', '潮州', '汕尾', '韶關', '陽江', '茂名', '湛江', '云浮'
];for i intup1:
city= str(i)#構建拼音,這樣每次就只要改這里的城市名就可以了
city = unicode(city, 'utf-8')
citypy=Pinyin() #實例化拼音模塊的函數
citypy=str(citypy.get_pinyin(city, '')) #還有其他轉換拼音的方法,比如在兩個字之間加符號等printcitypy
stradd='C://Users//Administrator//PycharmProjects//···//guangdong.txt'fh= open(stradd, "a")#輸入的文件編碼格式必須要與上面type=sys.setdefaultencoding( "utf-8" )一致,即也必須是utf-8
for page in range(1, 101):
test=ajkxq()#實例化對象
test.getInfo(page, fh, city, citypy)#方法必須由實例調用
fh.close()#time.sleep(3)#爬完一個城市后暫停3秒
end_time =time.time()print "數據爬取完畢,用時%.2f秒" % (end_time - start_time)
總結
以上是生活随笔為你收集整理的python 安居客 爬虫_Python爬虫安居客房价信息(并利用百度地图API查询坐标)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 硅谷就是这样
- 下一篇: 独立游戏人:像素风格游戏制作分享(转)
