【Class 47】【实例】python爬虫实现 搜索大量数据并保存在 excel 数据库中
现在 来写一个 爬虫,将搜索到的所有关键字,保存在 excel 数据库中
主要代码,在我们之前的博文中已经实现了
【Class 46】【实例】python爬虫实现 自动搜索 并 打开浏览器
我们在它的基础上来做改动
首先安装一下 pip install openpyxl 模块, 用于处理表格。
实现代码如下:
#! python3
# -*- coding: utf-8 -*-
# 搜索 python3.0 的搜狗搜索网址为:
# https://www.sogou.com/web?query=python3.0
import requests # 请求网页
import sys,os, webbrowser # 打开浏览器
import bs4 # 解析网页
from openpyxl import Workbook,load_workbook # 处理excel表格
def soup_compile(soup , sheet_t , str=''):
linkElems = soup.select( str )
#print("搜索到 rb 结果 ",len(linkElems)," 条结果\n")
row = sheet_t.max_row
# 依次保存到数据库,或者打印结果 str(i["href"]).startswith("http")
for i in linkElems:
row += 1
link_tmp = i["href"] if i['href'].startswith('http') else "https://www.sogou.com"+i["href"]
#print("网站:", i.getText().ljust(45,'-'),"---> 网址: ",link_tmp)
sheet_t["A%d"%row] = i.getText()
sheet_t["B%d"%row] = link_tmp
def sougou_get(content="", page=3, file_path=".\\search_result.xlsx"):
print('搜索内容为%s, 搜索%d页,保存在%s中 '%(content, page, os.path.abspath(file_path)))
if os.path.exists(file_path):
print("打开表格 : %s"%os.path.abspath(file_path) )
excel_fp = load_workbook(file_path , read_only=False)
else:
# 新建excel 表格
print("新建表格: %s"%os.path.abspath(file_path) )
excel_fp = Workbook()
try:
rb_sheet = excel_fp["rb_title"]
vrwrap_sheet = excel_fp["vrwrap_title"]
print("打开工作表 %s / %s"%("rb_title" , "vrwrap_title") )
except:
print("新建工作表 %s / %s"%("rb_title" , "vrwrap_title") )
# 创建 rb 和 vrwrap 两个 工作表
excel_fp.create_sheet(index=0, title="rb_title")
excel_fp.create_sheet(index=1, title="vrwrap_title")
rb_sheet = excel_fp["rb_title"]
vrwrap_sheet = excel_fp["vrwrap_title"]
rb_sheet['A1'] = "网站Title"
rb_sheet['B1'] = "网址"
vrwrap_sheet['A1'] = "网站Title"
vrwrap_sheet['B1'] = "网址"
for page_num in range(page):
# 获取命令行参数,拼凑url链接,并请求查找页面
#url_req = 'https://www.baidu.com/s?wd='+' '.join(sys.argv[1:])
url_req = 'https://www.sogou.com/web?query='+content+"&page=%d"%(page_num+1)
#print('搜索第%s页 ... url= '%(page_num + 1) , url_req)
res = requests.get(url_req)
# res.raise_for_status()
# 使用查找到的html网页 创建一个beautifulsoup对象,
# print(res.text)
soup = bs4.BeautifulSoup(res.text,'html.parser')
# rb 查找 class='pt' 中的<a></a> 的搜索结果
soup_compile(soup, rb_sheet, '.pt a')
# vrwrap 查找 class='vrTitle' 中的<a></a> 的搜索结果
soup_compile(soup, vrwrap_sheet, '.vrTitle a')
excel_fp.save(file_path)
print("保存表格 : %s"%os.path.abspath(file_path) )
if len(sys.argv) >= 2 :
sougou_get( ' '.join(sys.argv) ,50)
else:
sougou_get( "python3.0" , 50)
执行结果为:
# 第一次执行,文件不存在,新建文件
PS C:\Users\Administrator\Desktop\tmp> python .\auto_search.py
搜索内容为python3.0, 搜索50页,保存在C:\Users\Administrator\Desktop\tmp\search_result.xlsx中
新建表格: C:\Users\Administrator\Desktop\tmp\search_result.xlsx
新建工作表 rb_title / vrwrap_title
保存表格 : C:\Users\Administrator\Desktop\tmp\search_result.xlsx
PS C:\Users\Administrator\Desktop\tmp>
# 第二次执行,文件存在,打开文件
PS C:\Users\Administrator\Desktop\tmp> python .\auto_search.py
搜索内容为python3.0, 搜索50页,保存在C:\Users\Administrator\Desktop\tmp\search_result.xlsx中
打开表格 : C:\Users\Administrator\Desktop\tmp\search_result.xlsx
打开工作表 rb_title / vrwrap_title
保存表格 : C:\Users\Administrator\Desktop\tmp\search_result.xlsx
PS C:\Users\Administrator\Desktop\tmp>
excel 表格截图如下: