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

爬取代码:

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 爬虫的资料请关注其它相关文章!

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com