50 行代码爬取链家租房信息

最近自己开始学习数据分析的技术,但数据分析最重要的就是数据。没有数据怎么办?那就自己爬一些数据。大家一定要记得爬虫只是获取数据的一种手段,但如果不用一系列科学的方式去分析这些数据,那么爬去下来的数据是毫无用处的。所以爬虫进阶的方向很容易就可以对接到数据分析,我现在就是在往数据分析这个方向靠近。

而今天我们要分析的是链家上海出租房一些信息,从中找出性价比高的租房信息。这是一个系列的文章,我会从最开始的数据获取开始讲解,带大家一步步的完成一个数据分析的过程。话不多说,先来看下链家爬虫代码。

分析目标页面结构

写一个爬虫程序第一步就是分析下这个网页的请求结构和一些链接的变化情况,看看是不是否有规律可循,看看页面是否是动态加载,还是 ajax 加载的。

所以我们先打开链家的网站,先简单的浏览下。

简单的浏览之后,我们就很容易找到链家的规则,即链家下一页的链接都是把 url 最后的 pg 数字给修改下,直至最后一页。

这样我们的爬虫程序思路就有了,首先请求要爬取的页面,获取最大页数,然后用一个 for 循环请求页面直至结束。接下来看下具体的代码实现。

程序结构

程序结构很简单这里我创建了一个 LianJianSpider 的类,在初始化函数中,我定义了一些变量,其中还用到了之前给大家讲解到的 fake_useragent 库,用来随机生成请求头。

 

   def __init__(self):
        self.ua = UserAgent()
        self.headers = {"User-Agent": self.ua.random}
        self.datas = list()

get_max_page()

这个函数主要是用来获取当前页面的最大页数,即下面的图。

图中我圈了两个地方,第一个是页面上显示的内容。第二是浏览器控制台具体的数据位置,然后我通过 bs4 就可以获取当前最大页。

 

 def get_max_page(self, url):
        reponse = requests.get(url, headers=self.headers)
        if reponse.status_code == 200:
            source = reponse.text
            soup = BeautifulSoup(source, 'html.parser')
            a = soup.find_all("div", class_="page-box house-lst-page-box")
            max_page = eval(a[0].attrs["page-data"])["totalPage"]
            return max_page

        else:
            print("请求失败 statue: {}".format(reponse.status_code))
            return None

parse_page()

这个函数主要是用来进行翻页的操作,通过利用一个 for 循环来重构 url 实现翻页操作。而循环最大页数就是通过上面的 get_max_page() 来获取到。

再通过 BeautifulSoup 来获取每个租房信息的链接,然后通过 parse_detail() 这个解析函数,把具体的信息保存成一个字典,解析完一个页面就往 datas 这个列表中添加。最后所有的页面遍历完之后,在用 pandas 库把数据存储为 csv 文件,以便之后数据分析用。

 

    def pares_page(self, url):
        max_page = self.get_max_page(url)
        for i in range(1, max_page + 1):
            url = 'https://sh.lianjia.com/zufang/pa{}/'.format(i)
            print("当前正在爬取: {}".format(url))
            response = requests.get(url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'html.parser')
            a = soup.find_all("div", class_="info-panel")
            for j in range(len(a)):
                try:
                    link = a[j].find("a")["href"]
                    print(link)
                    detail = self.parse_detail(link)
                    self.datas.append(detail)
                except:
                    print('get page link is fail')
                    continue
        print("所有数据爬取完成,正在存储到 csv 文件中")
        data = pd.DataFrame(self.datas)
        data.to_csv("链家网租房数据.csv", encoding='utf_8_sig')

parse_detail()

租房页面信息提取函数,主要还是用了 BeautifulSoup 来进行数据的提取。

 

    def parse_detail(self, url):
        detail = {}
        response = requests.get(url, headers=self.headers)
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, "html.parser")
            b = soup.find("div", class_="content zf-content")
            detail["月租金"] = int(b.find("span", class_="total").text.strip())
            detail["面积"] = b.find_all("p", class_="lf")[0].text[3:].strip()
            detail["房屋户型"] = b.find_all("p", class_="lf")[1].text[5:].strip()
            detail["楼层"] = b.find_all("p", class_="lf")[2].text[3:].strip()
            detail["房屋朝向"] = b.find_all("p", class_="lf")[3].text[5:].strip()
            detail["地铁"] = b.find_all("p")[4].text[3:].strip()
            detail["小区"] = b.find_all("p")[5].text[3:].split('-')[0].strip()
            detail["位置"] = b.find_all("p")[6].text[3:].strip()
            return detail
        else:
            print("请求失败 statue: {}".format(reponse.status_code))
            return None

程序运行结果

程序运行完之后就会在当前目录下保存一份名为「链家网租房数据.csv」文件。

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/90071686
50