Python爬虫入门教程石家庄链家租房数据抓取
生活随笔
收集整理的這篇文章主要介紹了
Python爬虫入门教程石家庄链家租房数据抓取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
1. 寫在前面
這篇博客爬取了鏈家網的租房信息,爬取到的數據在后面的博客中可以作為一些數據分析的素材。
我們需要爬取的網址為:https://sjz.lianjia.com/zufang/
2. 分析網址
首先確定一下,哪些數據是我們需要的
?
可以看到,黃色框就是我們需要的數據。
接下來,確定一下翻頁規律
https://sjz.lianjia.com/zufang/pg1/ https://sjz.lianjia.com/zufang/pg2/ https://sjz.lianjia.com/zufang/pg3/ https://sjz.lianjia.com/zufang/pg4/ https://sjz.lianjia.com/zufang/pg5/ ... https://sjz.lianjia.com/zufang/pg80/?
3. 解析網頁
有了分頁地址,就可以快速把鏈接拼接完畢,我們采用lxml模塊解析網頁源碼,獲取想要的數據。
本次編碼使用了一個新的模塊?fake_useragent?,這個模塊,可以隨機的去獲取一個UA(user-agent),模塊使用比較簡單,可以去百度百度就很多教程。
本篇博客主要使用的是調用一個隨機的UA
self._ua = UserAgent() self._headers = {"User-Agent": self._ua.random} # 調用一個隨機的UA由于可以快速的把頁碼拼接出來,所以采用協程進行抓取,寫入csv文件采用的pandas模塊
from fake_useragent import UserAgent from lxml import etree import asyncio import aiohttp import pandas as pdclass LianjiaSpider(object):def __init__(self):self._ua = UserAgent()self._headers = {"User-Agent": self._ua.random}self._data = list()async def get(self,url):async with aiohttp.ClientSession() as session:try:async with session.get(url,headers=self._headers,timeout=3) as resp:if resp.status==200:result = await resp.text()return resultexcept Exception as e:print(e.args)async def parse_html(self):for page in range(1,77):url = "https://sjz.lianjia.com/zufang/pg{}/".format(page)print("正在爬取{}".format(url))html = await self.get(url) # 獲取網頁內容html = etree.HTML(html) # 解析網頁self.parse_page(html) # 匹配我們想要的數據print("正在存儲數據....")######################### 數據寫入data = pd.DataFrame(self._data)data.to_csv("鏈家網租房數據.csv", encoding='utf_8_sig') # 寫入文件######################### 數據寫入def run(self):loop = asyncio.get_event_loop()tasks = [asyncio.ensure_future(self.parse_html())]loop.run_until_complete(asyncio.wait(tasks))if __name__ == '__main__':l = LianjiaSpider()l.run()?
上述代碼中缺少一個解析網頁的函數,我們接下來把他補全
def parse_page(self,html):info_panel = html.xpath("//div[@class='info-panel']")for info in info_panel:region = self.remove_space(info.xpath(".//span[@class='region']/text()"))zone = self.remove_space(info.xpath(".//span[@class='zone']/span/text()"))meters = self.remove_space(info.xpath(".//span[@class='meters']/text()"))where = self.remove_space(info.xpath(".//div[@class='where']/span[4]/text()"))con = info.xpath(".//div[@class='con']/text()")floor = con[0] # 樓層type = con[1] # 樣式 agent = info.xpath(".//div[@class='con']/a/text()")[0]has = info.xpath(".//div[@class='left agency']//text()")price = info.xpath(".//div[@class='price']/span/text()")[0]price_pre = info.xpath(".//div[@class='price-pre']/text()")[0]look_num = info.xpath(".//div[@class='square']//span[@class='num']/text()")[0]one_data = {"region":region,"zone":zone,"meters":meters,"where":where,"louceng":floor,"type":type,"xiaoshou":agent,"has":has,"price":price,"price_pre":price_pre,"num":look_num}self._data.append(one_data) # 添加數據?
不一會,數據就爬取的差不多了。
轉載于:https://www.cnblogs.com/Anderson-An/p/10280304.html
總結
以上是生活随笔為你收集整理的Python爬虫入门教程石家庄链家租房数据抓取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序(六) 文章详情静态页面det
- 下一篇: synchronized 关键字解析