python 表格使用

例一 从表格中读出关键字,模拟浏览器搜索,将搜索到的关键字存入表格指定位置中。

'''
参考资料:https://www.cnblogs.com/insane-Mr-Li/p/9092619.html
https://www.cnblogs.com/machangwei-8/p/10739115.html
'''


from selenium import webdriver
import xlrd  #读excel的库
import xlwt  #写excel的库
from xlutils import copy #拷贝源文件


path="C:\\Users\wongwai\\Desktop\\wkym\\wk_bbs.xlsx"
workbook = xlrd.open_workbook(path,'w+b')  #打开excel文件读取数据
sheet = workbook.sheet_by_index(0) #通过索引顺序获取

wbook = copy.copy(workbook)#复制文件并保留格式
w_sheet = wbook.get_sheet(0)#索引sheet表
driver = webdriver.Chrome() #打开谷歌浏览器

for row in range(sheet.nrows):#按照行读取
		app_name = sheet.row(row)[1].value#获取表格中app的名字
		print(app_name)
		driver.get("https://topsearch.chinaz.net/Search.aspx?url=%u7F16%u7A0B%u8BBA%u575B")
		driver.find_element_by_xpath('//*[@id="txtKeyWord"]').clear()#清空文本框内容
		#模仿用户输入关键字
		driver.find_element_by_xpath('//*[@id="txtKeyWord"]').send_keys(app_name)  
		#模仿用户点击按钮
		driver.find_element_by_xpath('//*[@id="btnSearch"]').click()
		try:
			show = driver.find_element_by_xpath('//*[@id="ltArealist"]/li[1]/div[2]/h3/span')
			print(show.text)
			w_sheet.write(row, 3, show.text)#写入
		except Exception as e:
			print(e)


wbook.save(path)#保存文件

 例二  从表out_copy.xls中第一列数据如果与wk_bbs.xls中第三列数据值相同,将同行中的out_copy.xls的第二列数据复制到wk_bbs.xls的第四列中,形成新的表。

from selenium import webdriver
import xlrd
import xlwt
from xlutils import copy


path="C:\\Users\wongwai\\Desktop\\wkym\\wk_bbs.xlsx"  

path_out="C:\\Users\wongwai\\Desktop\\wkym\\out_copy.xls" 
 
workbook = xlrd.open_workbook(path,'w+b')  #读表格的行和列书
outbook = xlrd.open_workbook(path_out,'w+b')  #读表格的行和列书

sheet = workbook.sheet_by_index(0)
out_sheet = outbook.sheet_by_index(0)

wbook = copy.copy(workbook)#复制文件并保留格式
#obook = copy.copy(outbook)
w_sheet = wbook.get_sheet(0)
#o_sheet = obook.get_sheet(0)
for row in range(out_sheet.nrows):
	print (row)
	out_name = out_sheet.row(row)[0].value
	print (out_name)
	for j in range(sheet.nrows):#按照行读取
		app_name = sheet.row(j)[2].value#获取表格中app的名字
		
		if out_name==app_name:
			print (app_name)
			w_sheet.write(j, 3, out_sheet.row(row)[1].value)
	
	
wbook.save(path)
			
			

 

你可能感兴趣的:(【Python】)