加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

爬取两万多租房数据,告诉你广州房租现状

发布时间:2018-12-22 02:29:42 所属栏目:教程 来源:zone7
导读:概述 前言 统计结果 爬虫代码实现 爬虫分析实现 后记 前言 建议在看这篇文章之前,请看完这三篇文章,因为本文是依赖于前三篇文章的: 爬虫利器初体验(1) 听说你的爬虫又被封了?(2) 爬取数据不保存,就是耍流氓(3) 八月份的时候,由于脑洞大开,决定用 pyt

先解析首页 url

  1. def head_url_callback(self, response): 
  2.     soup = BeautifulSoup(response.body, "html5lib") 
  3.     dl = soup.find_all("dl", attrs={"id": "rentid_D04_01"})  # 获取各地区的 url 地址的 dl 标签 
  4.     my_as = dl[0].find_all("a")  # 获取 dl 标签中所有的 a 标签, 
  5.     for my_a in my_as: 
  6.         if my_a.text == "不限":  # 不限地区的,特殊处理 
  7.             self.headUrlList.append(self.baseUrl) 
  8.             self.allUrlList.append(self.baseUrl) 
  9.             continue 
  10.         if "周边" in my_a.text:  # 清除周边地区的数据 
  11.             continue 
  12.         # print(my_a["href"]) 
  13.         # print(my_a.text) 
  14.         self.allUrlList.append(self.baseUrl + my_a["href"]) 
  15.         self.headUrlList.append(self.baseUrl + my_a["href"]) 
  16.     print(self.allUrlList) 
  17.     url = self.headUrlList.pop(0) 
  18.     yield Request(url, callback=self.all_url_callback, dont_filter=True) 

再解析非首页 url

这里先获取到各个地区一共有多少页,才能拼接具体的页面地址。

爬取两万多租房数据,告诉你广州房租现状

  1. 再根据头部 url 拼接其他页码的url 
  2. ef all_url_callback(self, response): # 解析并拼接所有需要爬取的 url 地址 
  3.    soup = BeautifulSoup(response.body, "html5lib") 
  4.    div = soup.find_all("div", attrs={"id": "rentid_D10_01"})  # 获取各地区的 url 地址的 dl 标签 
  5.    span = div[0].find_all("span")  # 获取 dl 标签中所有的 span 标签, 
  6.    span_text = span[0].text 
  7.    for index in range(int(span_text[1:len(span_text) - 1])): 
  8.        if index == 0: 
  9.            pass 
  10.            # self.allUrlList.append(self.baseUrl + my_a["href"]) 
  11.        else: 
  12.            if self.baseUrl == response.url: 
  13.                self.allUrlList.append(response.url + "house/i3" + str(index + 1) + "/") 
  14.                continue 
  15.            self.allUrlList.append(response.url + "i3" + str(index + 1) + "/") 
  16.    if len(self.headUrlList) == 0: 
  17.        url = self.allUrlList.pop(0) 
  18.        yield Request(url, callback=self.parse, dont_filter=True) 
  19.    else: 
  20.        url = self.headUrlList.pop(0) 
  21.        yield Request(url, callback=self.all_url_callback, dont_filter=True) 

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读