Python 爬虫小练

这篇具有很好参考价值的文章主要介绍了Python 爬虫小练。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Python 爬虫小练 获取贝壳网数据

使用到的模块

标准库

Python3 标准库列表

  • os 模块:os 模块提供了许多与操作系统交互的函数,例如创建、移动和删除文件和目录,以及访问环境变量等。
  • math 模块:math 模块提供了数学函数,例如三角函数、对数函数、指数函数、常数等
  • datetime 模块:datetime 模块提供了更高级的日期和时间处理函数,例如处理时区、计算时间差、计算日期差等
  • logging 模块 :使用标准库提供的 logging API 最主要的好处是,所有的 Python 模块都可能参与日志输出,包括你自己的日志消息和第三方模块的日志消息。
  • logging.config 模块 :可配置 logging 模块。 它们的使用是可选的 — 要配置 logging 模块你可以使用这些函数,也可以通过调用主 API (在 logging 本身定义) 并定义在 logginglogging.handlers 中声明的处理器。
  • logging.handlers 模块 :这个包提供了以下有用的处理程序。 请注意有三个处理程序类 (StreamHandler, FileHandlerNullHandler) 实际上是在 logging 模块本身定义的,但其文档与其他处理程序一同记录在此。
  • urllib 模块:urllib 模块提供了访问网页和处理 URL 的功能,包括下载文件、发送 POST 请求、处理 cookies 等
  • threading 模块:线程模块提供对线程的支持
  • SQLite 3 模块:SQLite 是一个C语言库,它可以提供一种轻量级的基于磁盘的数据库,这种数据库不需要独立的服务器进程,也允许需要使用一种非标准的 SQL 查询语言来访问它。一些应用程序可以使用 SQLite 作为内部数据存储。可以用它来创建一个应用程序原型,然后再迁移到更大的数据库。

第三方库

  • requests 库: Python requests 是一个常用的 HTTP 请求库,可以方便地向网站发送 HTTP 请求,并获取响应结果。

    requests 模块比urllib模块更简洁。官网地址:Python requests

  • BeautifulSoup 库:是一个可以从HTML或XML文件中提取数据的Python库。官网地址:BeautifulSoup

使用到的相关逻辑步骤

请求URL

  • 模拟浏览器

    headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'
    }
    
  • URL编码

    import urllib.parse
    
    baseUrl = "https://nj.ke.com/ershoufang/"
    
    url = baseUrl + "天润城/"
    encoded_url = urllib.parse.quote(url, safe='/:?+=')
    
  • 无用户认证

    response = requests.get(encoded_url, headers=headers)
    
  • 有用户认证(cookie)

    headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
        'Cookie': 'lianjia_token=自己的具体值'
    }
    
    response = requests.get(encoded_url, headers=headers)
    
  • 代理,公司内部若存在代理需要配置。

    proxies = {"https": "http://111:8080"}
    
    response = requests.get(encoded_url, headers=headers, proxies=proxies)
    

解析HTML

soup = BeautifulSoup(response.text, 'html.parser')
  • 取属性

    soup.select('.title a')[0].attrs.get('href')
    
  • 取标签值

    soup.select(".total span")[0].text.strip()
    

下载图片资源

# urllib.request配置代理
urllib.request.install_opener(
  urllib.request.build_opener(
      urllib.request.ProxyHandler(proxies)
  )
)

urllib.request.urlretrieve(housingImgUrl,housingTypeImagePath)

分析数据

写入SQLite 3数据库

  • 建表(执行脚本)

  • 写入

  • 异常处理

    conn = sqlite3.connect('../db/identifier.sqlite', check_same_thread=False)
    c = conn.cursor()
    
    # 执行sql脚本
    with open('../db/script/house_listing_price.sql') as sql_file:
        c.executescript(sql_file.read())
    conn.commit()
    
    for house_info in house_info_list:
        sql = f'insert into house_listing_price values (' \
              f'"{house_info["houseid"]}"' \
              f',"{house_info["title"]}"' \
              f',"{house_info["price"]}"' \
              f',"{house_info["address"]}"' \
              f',"{house_info["area"]}"' \
              f',"{house_info["sealDate"]}"' \
              f',"{house_info["housingType"]}"' \
              f',"{house_info["houseUrl"]}")'
        try:
            c.execute("BEGIN")
            c.execute(sql)
            c.execute("COMMIT")
        except:
            print("[" + str(datetime.datetime.now()) + "] " + "写入数据库异常,sql is [" + sql + "]")
            c.execute("ROLLBACK")
    conn.commit()
    conn.close()
    

完整示例文章来源地址https://www.toymoban.com/news/detail-658724.html

import requests
from bs4 import BeautifulSoup
import math
import datetime
import sqlite3
import urllib.request
import os

# 代理-公司用
proxies = {"https": "http://111:8080"}
# 无代理
# proxies = {}

# 下载图片第三方配置代理
urllib.request.install_opener(
    urllib.request.build_opener(
        urllib.request.ProxyHandler(proxies)
    )
)

# 模拟浏览器请求的header
headers = {
    'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'
}

# 挂牌列表URL-不分页
url = "https://nj.ke.com/ershoufang/co22l2rs%E5%A4%A9%E6%B6%A6%E5%9F%8E%E5%8D%81%E5%9B%9B%E8%A1%97%E5%8C%BA/"
response = requests.get(url, headers=headers, proxies=proxies)
soup = BeautifulSoup(response.text, 'html.parser')
# 网站每页30条
everypagecount = 30
sumhouse = soup.select(".total span")[0].text.strip()
pagesum = int(sumhouse) / everypagecount
pagesum = math.ceil(pagesum)
# 网站只提供100页
pagesum = min(pagesum, 100)
print("[" + str(datetime.datetime.now()) + "] " + "总记录数" + str(sumhouse) + ",总页数" + str(pagesum))
# 创建一个空列表,用于存储房源信息
house_info_list = []


# 请求房源列表数据
def requestUrl(real_url):
    response = requests.get(real_url, headers=headers, proxies=proxies)
    soup = BeautifulSoup(response.text, 'html.parser')
    # 获取房源列表数据
    house_list = soup.select('.sellListContent li .clear')
    # 循环遍历房源列表,提取所需信息
    for house in house_list:
        # 挂牌标题
        title = house.select('.title a')[0].text.strip()
        # 挂牌价格
        price = house.select('.totalPrice span')[0].text.strip()
        # 地址小区名称
        address = house.select('.positionInfo a')[0].text.strip()
        # 楼层简述
        area = house.select('.houseInfo')[0].text.strip().replace(
            '\n', '').replace(' ', '').split('|')[0]
        area = area[0:area.index(')') + 1]
        # 房屋登记编号
        houseId = house.select('.unitPrice')[0].attrs.get('data-hid')
        # 房源详情页的URL
        href = house.select('.title a')[0].attrs.get('href')
        response2 = requests.get(href, headers=headers, proxies=proxies)
        soup2 = BeautifulSoup(response2.text, 'html.parser')
        # 挂牌日期
        sealDate = soup2.select('.introContent .transaction li')[0].text.strip()[4:]
        # 户型
        housingType = soup2.select('.introContent .base .content li')[0].text.strip()[4:].strip()
        # 房屋图片列表
        house_images_list = soup2.select('.thumbnail .smallpic li')
        housingTypeImagePath = "../src/main/resources/images/housingType/" + houseId + ".jpg"
        for house_images in house_images_list:
            # 下载户型图
            if "户型图" == house_images.attrs.get("data-desc") and not os.path.exists(housingTypeImagePath):
                housingImgUrl = house_images.attrs.get("data-src")
                urllib.request.urlretrieve(
                    housingImgUrl,
                    housingTypeImagePath)

        # 将提取到的信息添加到房源信息列表中
        house_info_list.append({
            'title': title,
            'price': price,
            'address': address,
            'area': area,
            'houseid': houseId,
            'sealDate': sealDate,
            'housingType': housingType,
            'houseUrl': href
        })
    return


pageNo = 0
while pageNo < pagesum:
    currentPageNo = str(pageNo + 1)
    # 挂牌列表URL-分页
    url = 'https://nj.ke.com/ershoufang/pg' + currentPageNo + 'co22l2rs%E5%A4%A9%E6%B6%A6%E5%9F%8E%E5%8D%81%E5%9B%9B%E8%A1%97%E5%8C%BA/'
    print("[" + str(datetime.datetime.now()) + "] " + "获取第" + currentPageNo + "页")
    requestUrl(url)
    pageNo = pageNo + 1

# 将房源信息列表保存为CSV文件
import csv

# print("写入文件中")
# current_date = datetime.datetime.now()
# formatted_date = current_date.strftime("%Y-%m-%d")
# filename = "house_info-" + formatted_date + ".csv"
# with open(filename, 'w', newline='', encoding='utf-8-sig') as f:
#     writer = csv.writer(f)
#     writer.writerow(['标题', '价格', '地址', '位置', '房屋ID'])
#     for house_info in house_info_list:
#         writer.writerow([
#             house_info['title'], house_info['price'], house_info['address'],
#             house_info['area'], house_info['houseid']
#         ])
# print("写入完成")

print("[" + str(datetime.datetime.now()) + "] " + "写入数据库")
conn = sqlite3.connect('../db/identifier.sqlite', check_same_thread=False)
c = conn.cursor()

# 执行sql脚本
with open('../db/script/house_listing_price.sql') as sql_file:
    c.executescript(sql_file.read())
conn.commit()

for house_info in house_info_list:
    sql = f'insert into house_listing_price values (' \
          f'"{house_info["houseid"]}"' \
          f',"{house_info["title"]}"' \
          f',"{house_info["price"]}"' \
          f',"{house_info["address"]}"' \
          f',"{house_info["area"]}"' \
          f',"{house_info["sealDate"]}"' \
          f',"{house_info["housingType"]}"' \
          f',"{house_info["houseUrl"]}")'
    try:
        c.execute("BEGIN")
        c.execute(sql)
        c.execute("COMMIT")
    except:
        print("[" + str(datetime.datetime.now()) + "] " + "写入数据库异常,sql is [" + sql + "]")
        c.execute("ROLLBACK")
conn.commit()
conn.close()
print("[" + str(datetime.datetime.now()) + "] " + "写入完成")

到了这里,关于Python 爬虫小练的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python实现网络爬虫代码_python如何实现网络爬虫

    python实现网络爬虫的方法:1、使用request库中的get方法,请求url的网页内容;2、【find()】和【find_all()】方法可以遍历这个html文件,提取指定信息。 python实现网络爬虫的方法: 第一步:爬取 使用request库中的get方法,请求url的网页内容 编写代码[root@localhost demo]# touch demo.py [

    2024年01月20日
    浏览(33)
  • Python小知识 - Python爬虫进阶:如何克服反爬虫技术

    Python爬虫进阶:如何克服反爬虫技术 爬虫是一种按照一定的规则,自动抓取网页信息的程序。爬虫也叫网页蜘蛛、蚂蚁、小水滴,是一种基于特定算法的自动化程序,能够按照一定的规则自动的抓取网页中的信息。爬虫程序的主要作用就是从一个网站或者一个网页中抓取所需

    2024年02月09日
    浏览(34)
  • 手机Python爬虫教程:利用手机学习Python爬虫的终极指南

    在数字化时代,手机已经成为人们生活中不可或缺的一部分。而Python爬虫作为一种强大的数据获取工具,也受到越来越多人的关注。但是,是否可以利用手机进行Python爬虫学习呢?本文将介绍如何通过手机学习Python爬虫,为你打开一扇全新的学习之门。 1. 《Python爬虫入门教程

    2024年02月07日
    浏览(41)
  • python爬虫入门教程(非常详细):如何快速入门Python爬虫?

    示例示例Python爬虫入门教程什么是爬虫爬虫(又称网络爬虫)是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。它可以自动地抓取网页内容,并从中提取有用的数据,存储到本地文件或数据库中。 Python爬虫入门教程 1. 什么是爬虫爬虫(又称网络爬虫)是一种

    2024年02月10日
    浏览(37)
  • Python爬虫 | 利用python爬虫获取想要搜索的数据(某du)

    这篇文章主要介绍了利用Python爬虫采集想要搜索的信息(利用某du的接口实现)并且处理掉它的反爬手段,文中示例代码很详细,具有一定的学习价值,感兴趣的小伙伴快来一起学习吧。 大家在日常生活中经常需要查找不同的事物的相关信息,今天我们利用python来实现这一个

    2024年02月01日
    浏览(32)
  • Python爬虫项目70例,附源码!70个Python爬虫练手实例

    今天博主给大家带来了一份大礼,Python爬虫70例!!!以及完整的项目源码!!! 本文下面所有的爬虫项目都有详细的配套教程以及源码,都已经打包好上传到百度云了,链接在文章结尾处! Python爬虫项目100例(一):入门级 1. CentOS环境安装 2. 和谐图网站爬取 3. 美空网数据

    2024年02月07日
    浏览(27)
  • Python 爬虫(一):爬虫伪装

    对于一些有一定规模或盈利性质比较强的网站,几乎都会做一些防爬措施,防爬措施一般来说有两种:一种是做身份验证,直接把虫子挡在了门口,另一种是在网站设置各种反爬机制,让虫子知难而返。 我们知道即使是一些规模很小的网站通常也会对来访者的身份做一下检查

    2024年02月05日
    浏览(41)
  • 【100天精通python】Day41:python网络爬虫开发_爬虫基础入门

    目录  专栏导读  1网络爬虫概述 1.1 工作原理 1.2 应用场景 1.3 爬虫策略

    2024年02月12日
    浏览(34)
  • 一个月学通Python(二十八):Python网络数据采集(爬虫)概述(爬虫)

    结合自身经验和内部资料总结的Python教程,每天3-5章,最短1个月就能全方位的完成Python的学习并进行实战开发,学完了定能成为大佬!加油吧!卷起来! 全部文章请访问专栏:《Python全栈教程(0基础)》 爬虫(crawler)也经常被称为网络蜘蛛(spider),是按照一定的规则自

    2024年02月14日
    浏览(41)
  • 【Python爬虫】Python爬虫三大基础模块(urllib & BS4 & Selenium)

    参考资料 Python爬虫教程(从入门到精通) Python urllib | 菜鸟教程 Beautiful Soup 4 入门手册_w3cschool Selenium入门指南 Selenium教程 什么是 Scrapy|极客教程 Scrapy入门教程 1、网络爬虫是什么? 我们所熟悉的一系列 搜索引擎都是大型的网络爬虫 ,比如百度、搜狗、360浏览器、谷歌搜索等

    2024年02月12日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包