初识爬虫——游天下 租房信息

昨今两天,学习了基本的爬虫,感受很不错,写下分享分享!!!css

首先,你们都关心的问题,学习爬虫须要具有什么知识呢??大体以下:html

  • python的基础知识(函数的定义、列表的操做、文件操做、正则表达式)难度:***
  • python额外知识(BeautifulSoup、requests、re(正则表达式))
  • html+css的基础知识(类选择器、id选择器以及dom)难度:******

而后就是作应该爬虫的基本流程:python

  1. 明确本身的目标,在哪一个网站爬取什么数据
  2. 分析单个页面中所需数据的获取规律
  3. 将规律提炼成函数
  4. 循环遍历获取数据
  5. 保存数据
  6. 分析数据

好比,假设咱们的任务以下:
正则表达式

经过这张图片咱们能够得到至少两个很重要的信息:chrome

  1. 目标网站
  2. 目标数据

接下来就是如何去制做爬虫,故,咱们要去学习相关的工具:浏览器

  1. BeautifulSoup(https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/)
  2. requests(https://cn.python-requests.org/zh_CN/latest/)

而后,咱们就能够对单个页面的数据进行分析了。例如:http://www.youtx.com/chengdu/page1/dom

首先咱们在浏览器中输入地址:
函数

而后,咱们能够(这里以chrome浏览器为例)按下F12,获得下面的画面:
工具

而后,咱们点击那个箭头:
学习

而后,选取咱们想看的部分,好比:

咱们就先点击刚刚那个箭头,而后点击那个地方,获得以下:

图中箭头所指即便该租房的主要信息页面,而后,咱们就点进去看看:

这儿就是咱们爬虫最主要的操做空间了,咱们所须要的许多信息都是从这里获取的
仍是上面说的那样,咱们先按F12,而后点击箭头,而后点击咱们关注的那个地方,好比说:

咱们能够经过观察html页面知道它的位置,而后,接下来的一步就是咱们怎样去找到它,若是咱们仔细观察,就会发现下面的信息:

咱们能够发现,它是位于class为housemessage的li的下面的,因而咱们知道,若是咱们要获取那个内容,就要先获取那个li标签再得到内容。
在css中咱们知道,一个类选择器能够对应着多个标签,可是一个id选择器则只能对应一个标签,因而,咱们须要知道该类选择器做用于那些标签,因而,咱们能够用下面的方法作(涉及js)

而后:

咱们发现恰好只有一个,可省下了很多事情。
经过上面的分析,因而咱们知道了一个大体的思路:在html中获取类名为housemessage的元素 ——>获取须要的值。
那么问题来了,咱们如何获得html页面,且如何获取元素呢,获取元素后咱们如何获取它的值呢???
这里,咱们就须要开始使用bs4模块和requests模块了。

以www.baidu.com为例:

# 第一步 导包
import requests
from bs4 import BeautifulSoup

# 第二步 获取目标网页的源代码
source = requests.get('www.baidu.com')
# 这里咱们能够看看source具备哪些方法和属性
print(dir(source))
print(source.__dict__)

# 第三步 美化源代码
soup = BeautifulSoup(source.text, 'html.parser')
# 看看效果
print(soup.prettify())

# 第四步 获取标签
print(soup.select(xxxx))

# 第五步 获取标签的值
print(soup.select(xxx).__dict__['contents'])

经过以上,咱们就能够在一个页面中获取咱们想要的数据了,那么多个页面爬取也就简单了,能够去寻找每个页面的规律,经过上面的方法,遍历获取每一个页面中理解,打开,获取数据,也能够是继续获取链接,一步步深刻。

如下就是完成上述任务的代码,能够参考参考,如有不足,请指正!!!谢谢!!!

# -*- coding:UTF-8 -*-
"""
Created on 2020/12/19 16:40

@author : Jonny Jiang
"""


import requests
import re
from bs4 import BeautifulSoup
import csv
import sys
import time

def get_info(url):
    content = requests.get(url)
    soup = BeautifulSoup(content.text, 'html.parser')
    housepercity = None  # 市
    housedistrict = None  # 区
    house_area = None  # 面积
    bedroom_num = 0 # 卧室数量
    bathroom_num = 0 # 卫生间数量
    house_style = None  # 房屋户型
    amount = None  # 宜住人数
    today_price = None  # 今日价格
    owner = None  # 租房人
    money = None  # 是否收取押金
    days = None  # 最短入住天数
    score = 0  # 整体评价
    result = []

    # 市区匹配表达式
    addr_1_p = "housepercity = (.+);"
    addr_2_p = "housedistrict = (.+);"

    housepercity = re.findall(re.compile(addr_1_p), soup.prettify())[0]
    housedistrict = re.findall(re.compile(addr_2_p), soup.prettify())[0]
    house_area = re.findall('\d+', soup.select('.housemessage span')[2].contents[0])[0]
    bedroom_num = re.findall('\d+', soup.select('.housemessage span')[-3].contents[0])
    if not bedroom_num:
        bedroom_num = 0
    else:
        bedroom_num = bedroom_num[0]
    bathroom_num = re.findall('\d+', soup.select('.housemessage span')[1].contents[0])
    if not bathroom_num:
        bathroom_num = 0
    else:
        bathroom_num = bathroom_num[0]
    house_style = (bedroom_num, bathroom_num)
    amount = re.findall('\d+', soup.select('.housemessage span')[-3].contents[0])[0]
    today_price = soup.select('.part-two p span')[0].__dict__.get('contents')[1]
    owner = soup.select(".left a")[0].__dict__['attrs']['title']
    money = soup.select('.dsection-4 span')[-4].__dict__['contents'][0][1:]
    days = soup.select('.dsection-4 span')[2].__dict__['contents'][0][0]
    score_s = soup.select('.sec-1 div')[0].get('class')
    score_int = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'half': 0.5}
    tmp = ''
    if len(score_s) > 1:
        for s in score_s[1][:-4]:
            tmp += s
            if tmp in score_int:
                score += score_int[tmp]
                tmp = ''
    result = [housepercity, housedistrict, house_area, house_style, amount, today_price, owner, money, days, score]

    return result


def main():
    page_url = 'http://www.youtx.com/chengdu/page{}/'

    # 保存文件名
    filename = 'test.csv'
    # 开始写入
    # filename = sys.argv[1]
    f = open(filename, 'w+', encoding='utf-8')
    csv_writer = csv.writer(f)
    csv_writer.writerow(['市', '区', '房屋面积', '房屋户型', '宜住人数', '当日出租价格', '租房人', '是否收取押金', '最短入住时间', '整体评价'])

    try:
        for i in range(1, 33):
            now_url = page_url.format(i)
            page = requests.get(now_url)
            soup = BeautifulSoup(page.text, 'html.parser')
            url_markups = soup.select('#results>ul>li')
            for url_markup in url_markups:
                url = url_markup.a.get('href')
                print(url)
                next_page = url
                result = get_info(next_page)
                print(result)
                csv_writer.writerow(result)
                time.sleep(0.5)
    finally:

        # 结束写入
        f.close()


if __name__ == '__main__':
    main()
相关文章
相关标签/搜索