Python+Selenium学习笔记15 - 读取txt和csv文件

时间:2024-09-24 19:37:26

读取txt的内容并用百度查找搜索

 1 # coding = utf-8
2
3 from selenium import webdriver
4 import time
5
6 # 打开浏览器
7 dr = webdriver.Firefox()
8 dr.get("http://www.baidu.com")
9
10 '''
11 # 读取列表的
12 words = ['python', 'selenium', 'webdriver']
13
14 for word in words:
15 dr.find_element_by_id("kw").clear()
16 dr.find_element_by_id("kw").send_keys(word)
17 dr.find_element_by_id("kw").submit()
18 time.sleep(5)
19
20 '''
21
22 # 打开文件并读取
23 f = open("word.txt", "r")
24 words = f.readlines()
25 f.close()
26
27 # 循环遍历txt内容再逐个查询
28 for word in words:
29 dr.find_element_by_id("kw").clear()
30 dr.find_element_by_id("kw").send_keys(word)
31 dr.find_element_by_id("kw").submit()
32 time.sleep(5)
33 print word
34
35
36 dr.quit()

txt文件内容

Python+Selenium学习笔记15 - 读取txt和csv文件

读取CSV文件

 1 import csv
2
3 # 读取本地CSV文件
4 f = csv.reader(open("file.csv", "r"))
5
6 for word in f:
7 print word
8
9 # 输出结果
10 ['apple', 'banana', 'cat']
11 ['dulian', 'ege', 'find']
12 ['go', 'hello', 'ip']
13 ['just', 'kind', 'len']
14 ['man', 'noon', '']

CSV文件内容

Python+Selenium学习笔记15 - 读取txt和csv文件

只读取某一列

 1 import csv
2
3 # 读取本地CSV文件
4 f = csv.reader(open("file.csv", "r"))
5
6 for word in f:
7 print word[1]
8
9
10 # 输出结果
11 banana
12 ege
13 hello
14 kind
15 noon