记一次python 爬虫爬取深圳租房信息的过程及遇到的问题

(编辑:jimmy 日期: 2024/9/21 浏览:2)

为了分析深圳市所有长租、短租公寓的信息,爬取了某租房公寓网站上深圳区域所有在租公寓信息,以下记录了爬取过程以及爬取过程中遇到的问题:

爬取代码:

import requests
from requests.exceptions import RequestException
from pyquery import PyQuery as pq
from bs4 import BeautifulSoup
import pymongo
from config import *
from multiprocessing import Pool

client = pymongo.MongoClient(MONGO_URL)  # 申明连接对象
db = client[MONGO_DB]  # 申明数据库

def get_one_page_html(url):  # 获取网站每一页的html
  headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
           "Chrome/85.0.4183.121 Safari/537.36"
  }
  try:
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
      return response.text
    else:
      return None
  except RequestException:
    return None


def get_room_url(html):  # 获取当前页面上所有room_info的url
  doc = pq(html)
  room_urls = doc('.r_lbx .r_lbx_cen .r_lbx_cena a').items()
  return room_urls


def parser_room_page(room_html):
  soup = BeautifulSoup(room_html, 'lxml')
  title = soup.h1.text
  price = soup.find('div', {'class': 'room-price-sale'}).text[:-3]
  x = soup.find_all('div', {'class': 'room-list'})
  area = x[0].text[7:-11]  # 面积
  bianhao = x[1].text[4:]
  house_type = x[2].text.strip()[3:7]  # 户型
  floor = x[5].text[4:-2]  # 楼层
  location1 = x[6].find_all('a')[0].text  # 分区
  location2 = x[6].find_all('a')[1].text
  location3 = x[6].find_all('a')[2].text
  subway = x[7].text[4:]
  addition = soup.find_all('div', {'class': 'room-title'})[0].text
  yield {
    'title': title,
    'price': price,
    'area': area,
    'bianhao': bianhao,
    'house_type': house_type,
    'floor': floor,
    'location1': location1,
    'location2': location2,
    'location3': location3,
    'subway': subway,
    'addition': addition
  }


def save_to_mongo(result):
  if db[MONGO_TABLE].insert_one(result):
    print('存储到mongodb成功', result)
    return True
  return False


def main(page):
  url = 'http://www.xxxxx.com/room/sz"text-align: center">记一次python 爬虫爬取深圳租房信息的过程及遇到的问题

上图中显示markup为None情况下报错,点击蓝色"F:\ProgramFiles\anaconda3\lib\site-packages\bs4\__init__.py"发现markup为room_html,即部分room_html出现None情况。要解决这个问题,必须让代码跳过room_html is None的情况,因此添加 if 语句解决了这个问题。

最终成功爬取某租房公寓深圳市258页共4755条租房信息,为下一步进行数据分析做准备。

记一次python 爬虫爬取深圳租房信息的过程及遇到的问题

其中单条信息:

记一次python 爬虫爬取深圳租房信息的过程及遇到的问题

以上就是记一次python 爬虫爬取深圳租房信息的过程及遇到的问题的详细内容,更多关于python 爬虫的资料请关注其它相关文章!

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。