首页 > 编程语言 >python进阶之路21 正则应用 第三方模块之requests模块 openpyxl模块 简易爬虫(pandas)

python进阶之路21 正则应用 第三方模块之requests模块 openpyxl模块 简易爬虫(pandas)

时间:2022-10-26 19:49:11浏览次数:47  
标签:进阶 python list 模块 print home complany data

作业讲解

"""
网络爬虫没有我们现在接触的那么简单
	有时候页面数据无法直接拷贝获取
	有时候页面还存在防爬机制 弄不好ip会被短暂拉黑
"""
http://www.redbull.com.cn/about/branch   红牛各公司信息
1.直接拷贝页面数据到本地文件
2.读取文件内容当作字符串处理
3.编写正则筛选内容
import re

# 1.文件操作读取文本内容
with open(r'redbull.html', 'r', encoding='utf8') as f:
# 2.直接读取全部内容 无需优化
    data = f.read()
# 3.研究各部分数据的特征 编写相应的正则表达式
"""
1.思路1:
    一次性获取每个公司全部的数据
    分部挨个获取最后统一整合
"""
res = re.findall("<h2>(.*?)</h2><p class='mapIco'>(.*?)</p><p class='mailIco'>(.*?)</p><p class='telIco'>(.*?)</p>",data)
# print(res)   # [(),(),(),()]
complany_title_list = re.findall('<h2>(.*?)</h2>', data)
# print(complany_title_list)
complany_address_list = re.findall("<p class='mapIco'>(.*?)</p>", data)
# print(complany_address_list)
complany_email_list = re.findall("<p class='mailIco'>(.*?)</p>", data)
# print(complany_email_list)
complany_phone_list = re.findall("<p class='telIco'>(.*?)</p>", data)
# print(complany_phone_list)
res = zip(complany_title_list,complany_address_list,complany_email_list,complany_phone_list)
# print(list(res))   # [(),(),(),()]
with open(r'comp_info.txt', 'w', encoding='utf')as f:
    for data_tuple in res:
        print(
            """
            公司名称:%s
            公司地址:%s
            公司邮编:%s
            公司电话:%s
            """ % data_tuple
        )
        f.write(
            """
            公司名称:%s
            公司地址:%s
            公司邮编:%s
            公司电话:%s\n
            """ % data_tuple)

第三方模块讲解

第三方模块:别人写的模块 一般情况下功能都特别强大
我们如果想使用第三方模块 第一次必须先下载 后面才可以反复使用(等同于内置模块)
下载第三方模块的方式
1.pip工具
注意每个解释器都有pip工具 如果我们的电脑上有多个版本的解释器那么 我们在使用pip的时候一定要注意到底使用的是哪一个版本 否则极其容易出现使用的是A版本解释器然后用B版本的pip下载的模块
    为了避免pip冲突 我们在使用的时候可以添加对应的版本
    python27     pip2.7
    python36     pip3.6
    python38     pip3.8
下载第三方模块的句式
    pip install 模块名
下载第三方模块临时切换仓库
    pip install 模块名 -i 仓库地址
下载第三方模块指定版本(不指定默认是最新版)
    pip install 模块名==版本号 -i 仓库地址   
2.pycharm提供快捷方式
    file---settings---project----python interpreter---界面双击搜索 install package
"""
下载第三方模块可能会出现的问题
1.报错并由警告信息
	WARNING: You are using pip version 20.2.1;
	原因在于pip版本过低 只需要拷贝和后面的命令执行更新操作即可
	d:\python38\python.exe -m pip install --upgrade pip
	更新完成后再次执行下载第三方模块的命令即可
2.报错并含有Timeout关键字
	说明当前计算机网络不稳定 只需要换网络或者重新执行几次即可
3.报错并没有关键字
	面向百度搜索
	pip下载XXX报错: 拷贝报错信息
	通常都是需要用户提前准备一些环境才可以顺利下载
4.下载速度很慢
	pip默认下载的仓库地址是国外的  python.org
	我们可以切换下载的地址
	pip install 模块名 -i 仓库地址
pip的仓库地址很多  直接搜
	清华大学 :https://pypi.tuna.tsinghua.edu.cn/simple/

	阿里云:http://mirrors.aliyun.com/pypi/simple/

	中国科学技术大学 :http://pypi.mirrors.ustc.edu.cn/simple/

	华中科技大学:http://pypi.hustunique.com/

	豆瓣源:http://pypi.douban.com/simple/

	腾讯源:http://mirrors.cloud.tencent.com/pypi/simple

	华为镜像源:https://repo.huaweicloud.com/repository/pypi/simple/
"""

网络爬虫模块之requests模块

requests能模拟浏览器发送网络请求 获取页面数据
import requests

# 1.朝指定网址发送请求获取页面数据(等价于:浏览器地址栏输入网址回车访问)
# res = requests.get('http://www.redbull.com.cn/about/branch')
# print(res)
# print(res.content)       # 获取bytes类型的网页数据(二进制)
# res.encoding = 'utf8'    # 指定编码
# print(res.text)          # 获取字符串类型的网页数据(默认按照utf8)
# res = requests.get('https://www.autohome.com.cn/beijing/')
# print(res.text)      # 汽车之家

网络爬虫实战之爬取链家二手房数据

import re

import requests

res = requests.get('https://sh.lianjia.com/ershoufang/pudong/')
# print(res.text)
data = res.text

home_title_list = re.findall('<a class="" href=".*?" target="_blank" data-log_index=".*?"  data-el="ershoufang" data-housecode=".*?" data-is_focus="" data-sl="">(.*?)</a>',data)
# print(home_title_list)
home_name_list = re.findall('<a href=".*?" target="_blank" data-log_index=".*?" data-el="region">(.*?) </a>',data)
# print(home_name_list)
home_street_list = re.findall('<div class="positionInfo"><span class="positionIcon"></span><a href=".*?" target="_blank" data-log_index=".*?" data-el="region">.*? </a>   -  <a href=".*?" target="_blank">(.*?)</a> </div>',data)
# print(home_street_list)
home_info_list = re.findall('<div class="houseInfo"><span class="houseIcon"></span>(.*?)</div>',data)
# print(home_info_list)
home_watch_list = re.findall('<div class="followInfo"><span class="starIcon"></span>(.*?)</div>',data)
# print(home_watch_list)
home_total_price_list = re.findall('<div class="priceInfo"><div class="totalPrice totalPrice2"><i> </i><span class="">(.*?)</span><i>万</i></div>',data)
# print(home_total_price_list)
home_unit_price_list = re.findall('<div class="unitPrice" data-hid=".*?" data-rid=".*?" data-price=".*?"><span>(.*?)</span></div></div>',data)
# print(home_unit_price_list)
home_data = zip(home_title_list,home_name_list,home_street_list,home_info_list,home_watch_list,home_total_price_list,home_unit_price_list)
# print(list(home_data))

with open(r'home_data.txt','w',encoding='utf8')as f:
    for data in list(home_data):
        print(
        """
        房屋标题:%s
        小区名称:%s
        街道名称:%s
        详细信息:%s
        关注程度:%s
        房屋总价:%s
        房屋单价:%s
        """ % data)
        f.write("""
            房屋标题:%s
            小区名称:%s
            街道名称:%s
            详细信息:%s
            关注程度:%s
            房屋总价:%s
            房屋单价:%s\n
            """ % data   )

自动化办公领域之openpyxl模块

1.excel文件的后缀名问题
     03版本之前
    	.xls
     03版本之后
    	.xlsx
2.操作excel表格的第三方模块
xlwt往表格中写入数据、wlrd从表格中读取数据
	兼容所有版本的excel文件
openpyxl最近几年比较火热的操作excel表格的模块
	03版本之前的兼容性比较差
ps:还有很多操作excel表格的模块 甚至涵盖了上述的模块>>>:pandas   

from openpyxl import Workbook


# 创建一个excel文件
wb = Workbook()
# 在一个excel文件内创建多个工作簿
wb1 = wb.create_sheet('帅哥')
wb2 = wb.create_sheet('美女')
wb3 = wb.create_sheet('大长腿')
# 还可以修改默认工作簿位置
wb4 = wb.create_sheet('富婆名单',0)

# 还可以二次修改工作簿名称
wb4.title = '高富帅排行榜'
# 还可以改工作簿的颜色
wb4.sheet_properties.tabColor = "1072BA"


# 填写数据的方式1
# wb4['F4'] = 666
# 填写数据的方式2
# wb4.cell(row=3, column=1, value='jason')
# # 填写数学公式
# wb4.cell(row=1, column=1, value=22222)
# wb4.cell(row=2, column=1, value=44444)
# wb4.cell(row=3, column=1, value=4444)
# wb4.cell(row=4, column=1, value=4444)
# wb4['A5'] = '=sum(A1:A4)'
# wb4.cell(row=8,column=5,value='=sum(A1:A4)')
# 填写数据的方式3
# wb4.append(['编号','年龄','姓名','爱好'])   # 表头字段
# wb4.append(['1','12','jason','111'])
# wb4.append(['2','13','kevin','222'])
# wb4.append(['3','14','jerry','333'])
# wb4.append(['4','16','tom','444'])
'''多了少了 正常写入'''

# 保存excel文件
wb.save(r'111.xlsx')    

"""
openpyxl主要用于数据的写入 至于后续的表操作它并不是很擅长 如果想做需要更高级的模块pandas
import pandas

data_dict = {
    "公司名称":complany_title_list,
    "公司地址":complany_address_list,
    "公司邮编":complany_email_list,
    "公司电话":complany_phone_list}
# 将字典转换成pandas 里面的DataFrame数据结构
df = pandas.DataFrame(data_dict)
# 直接保存成excel文件
df.to_excel(r'pd_comp_info.xlsx')

excel软件正常可以打开操作的数据集在10万左右 一旦数据集过大 软件操作几乎无效
需要使用代码操作>>>:pandas模块
"""
openpyxl读取数据
from openpyxl import load_workbook

# 1.指定读取的文件
wb = load_workbook(r'111.xlsx',data_only=True)
# 2.查看内部所有工作薄名称
# print(wb.sheetnames)  # ['高富帅排行榜', 'Sheet', '帅哥', '美女', '大长腿']
# 3.指定某个工作薄
wb1 = wb['帅哥']
# 4.读取工作薄相关操作
# print(wb1.max_row)  # 获取最大列数
# print(wb1.max_column)  # 获取最大行数
# print(wb1['A3'].value)  # 读取单元格内容
# print(wb1['A8'].value)  # 如果是公式 读取的是公式    如果想要读取结果 需要加参数data_only

# for i in wb1.rows:
#     print([d.value for d in i])
# for j in wb1.rows:
#     print([d.value for d in j])

import pandas

print(pandas.read_excel(r'111.xlsx', ))

标签:进阶,python,list,模块,print,home,complany,data
From: https://www.cnblogs.com/xm15/p/16829761.html

相关文章

  • 第三方模块的下载与使用 requests模块 openpyxl模块
    今日内容第三方模块下载操作第三方模块:别人写的魔魁啊一般情况下都很强大python中模块很多如果想使用第三方模块第一次必须先下载后面就可以反复使用=内置......
  • 23、python模块篇 第三方模块、requests模块、openpyxl模块
    目录一、第三方模块的下载与使用1、什么是第三方模块2、如何安装第三方模块方式一:pip工具方式二:pycharm中下载3、注意事项1、报错并有警告信息2、报错,提示关键字3、报错,无......
  • 第三方模块
    python第三方模块下载与安装第三方模块,也就是其他大佬写好的模块,它的功能一般是十分强大的,但是,在我们使用前需要进行下载,好处就是,第一次下载完毕后,我们就相当于将这个第......
  • 第三方模块下载与使用
    今日内容总结第三模块下载与使用第三方模块:别人写的模块一般情况下功能都特别强大我们如果想使用第三方模块第一次必须先下载后面才可以反复使用(等同于内置模......
  • 网络爬虫之requests模块
    第三方模块的下载与使用网络爬虫模块之requests模块网络爬虫实战之爬取链接二手房数据自动化办公领域之openpyxl模块第三方模块的扩展(模块叠模块)网络爬虫之小实战......
  • requests模块/openpyxl模块/简单爬虫实战
    内容概要第三方模块的下载及使用网络爬虫及requests模块网络爬虫实战爬取二手房信息自动化办公领域模块openpyxl练习题及答案第三方模块的下载第三方模块就类似与......
  • 网络爬虫及openyxl模块
    网络爬虫及openyxl模块一、第三方模块简介1.第三方模块的用处python之所以在这么多的编程语言中脱颖而出的优点是有众多的第三方库函数,可以更高效率的实现开发2.......
  • python协程
    1、概念协程,又称微线程。协程是python个中另外一种实现多任务的方式,只不过比线程更小占用更小执行单元(理解为需要的资源)。为啥说它是一个执行单元,因为它自带CPU上下文。......
  • 【python】创意二维码那么多,咋不的掺和一下整一手~
    前言嗨喽~大家好呀,这里是魔王呐!网上有很多的创意二维码,看了,别的不说羡慕肯定是有的,羡慕有了这不得自己整点活~今天我们就来试试只用几行代码,生成动态二维码!开发环......
  • python numpy 基础科学计算包,数学函数库
    pipinstallnumpynumpy.array()函数,强大的N维数组对象ndarrayimportnumpyasnpa=np.array([1,2,3])print(a)[123]#多于一个维度importnumpyasnpa......