第三方模块与爬虫初体验

232 阅读5分钟

网络爬虫简介

1.什么是互联网
	将全世界的计算机连接到一起组成的网络
2.互联网发明的目的是什么
	将接入互联网的计算机上面的数据彼此共享
3.上网的本质是什么
	基于互联网访问别人计算机上面的资源(有些计算机存在的意义就是让别人访问,这种类型的计算机我们也称之为服务器)
4.网络爬虫的本质
	模拟计算机浏览器朝目标网址发送请求回去数据并筛选
    只要是浏览器可以访问到的数据网络爬虫理论上都可以
5.网络爬虫依赖于requests模块,这个第三方模块需要我们提前下载

第三方模块下载

1.第三方模块使用前必须先在本地下载
2.python下载第三方模块可以借助pip工具
  下载命令: pip38 install 模块名
    """
pip下载中可能遇到的问题
1.下载速度很慢
	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/
换源下载命令:pip3.8 install 模块名 -i 源地址
2.下载报错
	2.1.pip工具版本过低 直接拷贝提示信息里面的更新命令即可
		python38 -m pip install --upgrade pip
	2.2.网络波动 关键字是Read timed out
		只需要重新下载几次即可 或者切换一个网络稳定一点的
	2.3.有些模块在下载使用之前需要提前配置指定的环境
		结合具体情况 百度搜索
3.模块也有版本
	pip3.8 install 模块名==版本号
		pip3.8 install django==1.11.11
	"""
3.利用pycharm下载模块  

点击 左上角File ===> Settings 进入以下界面

1.png

2.png

网络爬虫实战

一切准备就绪,我们可以愉快地爬取网页信息了。我们以获取红牛分公司网页为例:www.redbull.com.cn/about/branc…

import requests
import re

# 朝目标网站发送请求获取相应数据(相当于在浏览器地址栏输入该网址并回车)
res = requests.get('http://www.redbull.com.cn/about/branch')
# print(res.content)  # 获取bytes类型的数据
# print(res.text)  # 获取解码之后的数据
# 为了避免每次执行程序都要发送请求,我们可以先将页面数据保存到文件中
with open(r'redbull.html', 'wb') as f:
    f.write(res.content)

# 读取页面数据
with open(r'redbull.html', 'r', encoding='utf8') as f:
    res = f.read()
# 研究目标数据的特征 编写正则筛选
# 1.获取所有分公司名称
commapy_name_list = re.findall('<h2>(.*?)</h2>', res)
# print(commapy_name_list)
# 2.获取所有分公司公司地址
company_addr_list = re.findall("<p class='mapIco'>(.*?)</p>", res)
# print(company_addr_list)
# 3.获取所有分公司的邮箱
company_mail_list = re.findall("<p class='mailIco'>(.*?)</p>", res)
# print(company_mail_list)
# 4.获取所有分公司的联系电话
company_tel_list = re.findall("<p class='telIco'>(.*?)</p>", res)
# print(company_tel_list)
# 5.将上述数据按照位置整合
res1 = zip(commapy_name_list, company_addr_list, company_mail_list, company_tel_list)
# print(res1)  # <zip object at 0x0000028A084A3FC0>
# 6.处理数据写入文件
with open('redbull_info.txt', 'a', encoding='utf8') as f:
    for i in res1:
        f.write(f'公司名称:{i[0]}, 公司地址:{i[1]}, 公司邮箱:{i[2]}, 公司电话:{i[3]} \n')

爬取的信息如下图所示

3.png

openpyxl模块简介

openpyxl模块主要用户操作excel表格,也是pandas底层操作表格的模块
在python中能够操作excel表格的模块有很多
	openpyxl属于近几年比较流行的模块,openpyxl针对03版本之前的excel文件兼容性不好
	xlwt、xlrd也可以操作excel表格,兼容所有版本的excel文件 但是使用方式没有openpyxl简单
1.excel版本问题
	03版本之前 excel文件的后缀名 .xls
 	03版本之后 excel文件的后缀名 .xlsx
    	如果是苹果电脑excel文件的后缀 .csv
2.下载模块
	pip3.8 install openpyxl	

openpyxl写入数据实操

from openpyxl import Workbook
1.创建excel文件
    # 1.创建excel文件
    wb = Workbook()
    # 2.新增sheet
    wb1 = wb.create_sheet('成绩表')
    wb2 = wb.create_sheet('编号表')
    # 3.支持二次修改
    wb1.title = '舔狗表'
    # 修改工作簿颜色
    wb1.sheet_properties.tabColor = "1072BA"
    # 保存文件
    wb.save(r'111.xlsx')  # 保存文件
2.写入数据    
    # 第一种写入方式:指定单元格写入
    wb1['A1'] = '叙利亚'
    # 第二种写入方式:按行列信息写入
    wb1.cell(row=3, column=2, value='我是老六')
    # 第三种写入方式:批量写入
    wb1.append(['username', 'password', 'age', 'gender', 'hobby'])
    wb1.append(['jason1', 123, 18, 'male', 'read'])
    wb1.append(['jason2', 123, 18, 'male', 'read'])
    wb1.append(['jason3', 123, 18, 'male', 'read'])
    wb1.append(['jason4', 123, 18, 'male', 'read'])
    wb1.append(['jason4', 123, 18, 'male', None])
    wb1.append([None, 123, 18, 'male', ''])
    # 还支持数学计算
    wb1['F11'] = '=sum(B5:B10)'

openpyxl读取数据

wb = load_workbook(r'111.xlsx',data_only=True)
# print(wb.sheetnames)  # 查看excel文件中所有的工作簿名称  ['红浪漫消费记录', 'Sheet', '天上人间消费记录', '白马会所消费记录']
wb1 = wb['红浪漫消费记录']
print(wb1.max_row)
print(wb1.max_column)
print(wb1['A1'].value)
print(wb1.cell(row=2,column=2).value)  # 第二种取值方式

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

for j in wb1.columns:
    print([i.value for i in j])
"""
openpyxl不擅长读数据,所以有一些模块优化了读取的方式:pandas模块
"""

爬虫与excel操作结合使用

# 需求:将红牛分公司数据保存到excel表格中

import requests
import re
from openpyxl import Workbook
# 获取网页信息
base = requests.get('http://www.redbull.com.cn/about/branch')
# 为了避免每次执行程序都要发送请求,我们可以先将页面数据保存到文件中
with open(r'redbull.html', 'wb') as f:
    f.write(base.content)
# 读取页面数据
with open(r'redbull.html', 'r', encoding='utf8') as f:
    res = f.read()
# 1.获取所有分公司名称
commapy_name_list = re.findall('<h2>(.*?)</h2>', res)
# 2.获取所有分公司公司地址
company_addr_list = re.findall("<p class='mapIco'>(.*?)</p>", res)
# 3.获取所有分公司的邮箱
company_mail_list = re.findall("<p class='mailIco'>(.*?)</p>", res)
# 4.获取所有分公司的联系电话
company_tel_list = re.findall("<p class='telIco'>(.*?)</p>", res)
# 5.将上述数据按照位置整合
res = zip(commapy_name_list, company_addr_list, company_mail_list, company_tel_list)
# 创建excel文件
wb = Workbook()
wb1 = wb.create_sheet('红牛企业信息表')
wb1.append(['公司名称', '公司地址', '公司邮箱', '公司电话'])
# 循环写入
for i in res:
    wb1.append(list(i))
wb.save(r'红牛企业信息表.xlsx')

爬虫练习之爬取链家二手房数据

import re

import pandas
import requests

# res = requests.get('https://sh.lianjia.com/ershoufang/')
# with open(r'lj.html','wb') as f:
#     f.write(res.content)
with open(r'lj.html', 'r', encoding='utf8') as f:
    data = f.read()

# 研究房屋信息
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
)
home_name_list = re.findall(
    '<a href=".*?" target="_blank" data-log_index=".*?" data-el="region">(.*?) </a>',
    data
)
home_addr_list = re.findall(
    '   -  <a href=".*?" target="_blank">(.*?)</a>',
    data
)
home_info_list = re.findall(
    '<div class="houseInfo"><span class="houseIcon"></span>(.*?)</div>',
    data
)
home_others_list = re.findall(
    '<div class="followInfo"><span class="starIcon"></span>(.*?)</div>',
    data
)
home_total_price = re.findall(
    '<div class="totalPrice totalPrice2"><i> </i><span class="">(.*?)</span><i>万</i></div>',
    data
)
home_unit_price = re.findall(
    '<div class="unitPrice" data-hid=".*?" data-rid=".*?" data-price=".*?"><span>(.*?)</span></div>',
    data
)
d = {
    '房屋标题': home_title_list,
    '小区名称': home_name_list,
    '所在街道': home_addr_list,
    '具体信息': home_info_list,
    '其他信息': home_others_list,
    '房屋总价': home_total_price,
    '房屋单价': home_unit_price
}
df = pandas.DataFrame(d)
df.to_excel(r'333.xlsx')