Python学习 Day52 Python与MongoDB的交互操作 04

案例——链家二手房

网址:https://bj.lianjia.com/ershoufang/
数据:Python与MySQL交互操作案例

1.创建存储数据库

在mongo.exe软件中输入以下代码
在这里插入图片描述
在这里插入图片描述

2.代码
import requests
from bs4 import BeautifulSoup
import pymongo

class LianJiaSpider():


    def __init__(self):
        self.url = 'http://bj.lianjia.com/ershoufang/pg{0}/' #{
    
    0}表示字符串的格式化
        self.heasers = {
    
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'}

    def send_requests(self,url):
        '''发送请求'''
        resp = requests.get(url,headers=self.heasers)
        if resp.status_code == 200:  #判断响应状态码,200时正常返回数据
            return resp

    def parse_html(self,resp):
        '''解析数据'''
        lst = [] #用于存放数据
        html = resp.text
        bs = BeautifulSoup(html,'lxml')
        ul = bs.find('ul',class_='sellListContent')
        li_list = ul.find_all('li')
        #print(len(li_list))  #检查是否获取到数据
        for item in li_list:
            title = item.find('div',class_='title').text #循环获得标题的文本内容
            houseInfo = item.find('div',class_='houseInfo').text #获取每套房子的房型信息
            positionInfo = item.find('div',class_='positionInfo').text #获取每套房子的位置信息
            totalPrice = item.find('div',class_='totalPrice').text #获取每套房子的销售总价
            unitPrice = item.find('div',class_='unitPrice').text #获取每套房的单价
            followInfo = item.find('div',class_='followInfo') #获得每套房的关注信息
            if followInfo != None:           #去除空值数据
                followInfo = followInfo.text
            else:
                followInfo = ''
            #print(title) #输出房名
            #print(houseInfo) #输出房型信息
            #print(positionInfo)  # 输出位置信息
            #print(totalPrice) #输出销售总价
            #print(unitPrice) #输出房屋单价信息
            #print(followInfo) #输出每套房的关注信息
            lst.append({
    
    'title':title,
                        'houseInfo':houseInfo,
                        'positionInfo':positionInfo,
                        'totalPrice':totalPrice,
                        'unitePrice':unitPrice,
                        'followInfo':followInfo})
        #print(lst)
        self.save(lst) #调用save函数存储数据

    def save(self,lst):
        '''存储数据'''
        #获取连接对象
        client = pymongo.MongoClient('localhost',27017)
        #获取要操作的数据库
        db = client['lianjia']
        #获取collection
        collection = db['collection_lianjia']
        #向集合中插入数据
        collection.insert_many(lst)

    def start(self):
        '''启动爬虫程序'''
        for i in range(1,2): #当前只爬取一页数据,若为多页修改range函数范围即可
            full_url = self.url.format(i) #完整URL的拼接
            resp = self.send_requests(full_url) #拼接后发送请求
            #print(resp.text)
            self.parse_html(resp)

if __name__ == '__main__':
    lianjia = LianJiaSpider()
    lianjia.start()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ShengXIABai/article/details/116608506
今日推荐