用爬虫收集网站公开数据丨Python爬虫实战系列

用爬虫收集网站公开数据丨Python爬虫实战系列,第1张

提示:最新Python爬虫资料/代码练习>>戳我直达

文章目录
  • 前言
  • 用爬虫收集公开数据
    • 编写程序流程分析
    • 确定Xpath表达式
        • 1) 确定基准表达式
        • 2) 确定抓取信息的表达式
        • 3) 提高抓取效率
    • 编写程序代码
  • 小结


前言

lxml 解析库的应用

在编写此程序的过程中,您将体会到 lxml 解析库的实际应用。

话不多说,开练!

用爬虫收集公开数据 编写程序流程分析

打开网站后,第一步,确定网站是否为静态网站,通过在网页源码内搜索关键字的方法,可以确定其为静态网站;第二步,确定要抓取页面的 URL 规律,第三步,根据要抓取的数据确定 Xpath 表达式;最后一步,编写 Python 爬虫程序。

通过简单的分析可知 URL 具有以下规律:

确定Xpath表达式

使用 Chrome 开发者工具对页面元素进行审查,从而确定 Xpath 表达式。首先根据要抓取的数据确定“基准表达式”。通过审查一处房源的元素结构,可以得知房源信息都包含在以下代码中:

1) 确定基准表达式

待抓取的信息都包含在相应的

标签中,如下所示:

"positionInfo">..
"address">...
"priceInfo">...

而每个页面中都包含 30 个房源,因此我们要匹配以下节点的父节点或者先辈节点,从而确定 Xpath 基准表达式:

"info clear">

通过页面结构分析可以得出每页的 30 个房源信息全部包含以下节点中:

    "sellListContent" log-mod="list">
  • "clear LOGVIEWDATA LOGCLICKDATA"> 房源信息..

接下来,使用调试工具定位上述元素,然后滚动鼠标滑。这时候神奇的一幕出现了,你会发现li标签的class属性值发生了变化,其结果如下:

    "sellListContent" log-mod="list">
  • "clear LOGCLICKDATA"> 房源信息..

发生变化的原因是由于 JS 事件触发导致的。因此就需要去页面的源码页进行匹配。

下面使用Ctrl+F分别对 class 变化前后的属性值进行检索,最后发现源码页只存在如下属性:

class="clear LOGVIEWDATA LOGCLICKDATA"

因此 Xpath 基准表达式如下所示:

//ul[@class="sellListContent"]/li[@class="clear LOGVIEWDATA LOGCLICKDATA"]
2) 确定抓取信息的表达式

根据页面元素结构确定待抓取信息的 Xpath 表达式,分别如下:

小区名称:name_list=h.xpath('.//a[@data-el="region"]/text()')
房屋介绍:info_list=h.xpath('.//div[@]/text()')
地址信息:address_list=h.xpath('.//div[@]/a/text()')
单价信息:price_list=h.xpath('.//div[@]/span/text()')

其中房屋介绍,主要包含了以下信息:

因此,匹配出的 info_list 列表需要经过处理才能得出我们想要的数据,如下所示:

info_list=h.xpath('.//div[@]/text()')
if info_list:
   #处理列表数据
   L=info_list[0].split('|')
   # ['2室1厅 ', ' 88.62平米 ', ' 北 南 ', ' 简装 ', ' 顶层(共6层) ', ' 2004年建 ', ' 板楼']
   if len(L) >= 5:
      item['model']=L[0].strip()
      item['area']=L[1].strip()
      item['direction']=L[2].strip()
      item['perfect']=L[3].strip()
      item['floor']=L[4].strip()
3) 提高抓取效率

为了提高网页信息的抓取质量,减小网络波动带来的响应,我们可以设置一个规则:在超时时间内(3秒),在该时间内对于请求失败的页面尝试请求三次,如果均未成功,则抓取下一个页面。

requests.get() 方法提供了 timeout 参数可以用来设置超时时间,此方法还提供了其他实用性参数,比如 auth(用户认证)、veryify(证书认证)、proxies(设置代理 IP),这在后续内容中会做相应介绍。

编写程序代码

通过上述分析得出了所有的 Xpath 表达式,下面开始编写爬虫程序,代码如下:

  • 代码不要拿来就用,仔细看看,主要是学习阿星的方法
#coding:utf8
import requests
import random
from lxml import etree
import time
#提供ua信息的的包
from fake_useragent import UserAgent

class LinajiaSpider(object):
    def __init__(self):
        self.url='https://lj网址/ershoufang/pg{}/'
        #计数,请求一个页面的次数,初始值为1
        self.blog=1

    # 随机取一个UA
    def get_header(self):
        #实例化ua对象
        ua=UserAgent()
        headers={'User-Agent':ua.random}
        return headers
    #发送请求
    def get_html(self,url):  
       #在超时间内,对于失败页面尝试请求三次
        if self.blog<=3:
            try:
                res=requests.get(url=url,headers=self.get_header(),timeout=3)
                html=res.text
                return html
            except Exception as e:
                print(e)
                self.blog+=1
                self.get_html(url)

    # 解析提取数据
    def parse_html(self,url):
        html=self.get_html(url)
        if html:
            p=etree.HTML(html)
            #基准xpath表达式-30个房源节点对象列表
            h_list=p.xpath('//ul[@]/li[@]')
            #所有列表节点对象
            for h in h_list:
                item={}
                #名称
                name_list=h.xpath('.//a[@data-el="region"]/text()')
                #判断列表是否为空
                item['name']=name_list[0] if name_list else None
    #户型+面积+方位+是否精装..['2室1厅 | 88.62平米 | 北 南 | 简装 | 顶层(共6层) | 2004年建 | 板楼']
                info_list=h.xpath('.//div[@]/text()')
                #判断列表是否为空
                if info_list:
                    L=info_list[0].split('|')
          # ['2室1厅 ', ' 88.62平米 ', ' 北 南 ', ' 简装 ', ' 顶层(共6层) ', ' 2004年建 ', ' 板楼']
                    if len(L) >= 5:
                        item['model']=L[0].strip()
                        item['area']=L[1].strip()
                        item['direction']=L[2].strip()
                        item['perfect']=L[3].strip()
                        item['floor']=L[4].strip()
                #区域+总价+单价

                address_list=h.xpath('.//div[@]/a/text()')
                item['address']=address_list[0].strip() if address_list else None

                total_list=h.xpath('.//div[@]/span/text()')
                item['total_list']=total_list[0].strip() if total_list else  None

                price_list=h.xpath('.//div[@]/span/text()')
                item['price_list']=price_list[0].strip() if price_list else None
                print(item)

     # 入口函数
    def run(self):
        try:
            for i in range(1,101):
                url=self.url.format(i)
                self.parse_html(url)
                time.sleep(random.randint(1,3))
                #每次抓取一页要初始化一次self.blog
                self.blog=1
        except Exception as e:
            print('发生错误',e)

if __name__ == '__main__':
    spider=LinajiaSpider()
    spider.run()

展示部分输出结果:


小结

用爬虫收集二手房数据丨Python基础实战系列(5) 就到这啦,在学爬虫的老铁记得持续关注!阿星祝你早日修炼成为爬虫大佬!点我文末的名片【领取阿星精心准备的Python学习籽料~】

戳名片找我🧐给你来一套

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/920762.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存