1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 | from selenium import webdriver
import time
#chromedriver.exe執行檔所存在的路徑 須配合電腦上的chrome版本
# chrome_path =r"C:\Users\trico\Desktop\chromedriver\chromedriver.exe"
chrome_path =r"D:\chromedriver_win32\chromedriver.exe"
options = webdriver.ChromeOptions() #透過options紀錄webdriver.ChromeOptions()的設定
options.add_argument("--headless") #增加啟動參數,瀏覽器頁面不可視化(背景執行)
browser = webdriver.Chrome(chrome_path,options=options) #webdriver.Chrome的設定選項
# browser = webdriver.Chrome(chrome_path)
#讀取資料
f = open("url.csv","r") #如果檔案編碼是utf-8 要再加上 ,encoding="utf-8"
s = f.readlines()
c = "科目,示例名稱,網址,介紹\n" #設定寫出檔案的第一行
for i in range(1,len(s)):
url=s[i]
list=url.split(",") #分割串列
# print(list[2].replace('\n','')) #第3筆是最後1筆資料會有換行符號,須去掉
browser.get(list[2].replace('\n','')) #載入網址
time.sleep(3) #等待3秒載入網頁
tag = browser.find_element_by_id('description') #資訊所在的DIV id
tag2=tag.text.replace('\n','').replace('\r','') #用空字串取代所有換行符號 ,不能用strip刪除
# print(tag2)
# print(len(tag2))
# 因為沒有資訊也同樣能抓到空字串,不會出現錯誤
# try:
# tag = browser.find_element_by_id('description')
# tag2=tag.text.replace('\n', '').replace('\r', '')
# c +="{},{},{},{}".format(list[0],list[1],list[2],tag2)
# print(c)
# except:
# c +="{},{},{},{}".format(list[0],list[1],list[2],"無說明")
# continue
# print(c)
# 改用 if判斷 len(tag2)是否>0
if i < len(s)-1: #如果不是最後一筆才加分行符號
if len(tag2) > 0 :
#print(tag2)
c +="{},{},{},{}\n".format(list[0],list[1],list[2].replace('\n',''),tag2)
else:
tag2="無內容資訊"
c +="{},{},{},{}\n".format(list[0],list[1],list[2].replace('\n',''),tag2)
#print(tag2)
else:
if len(tag2) > 0 :
#print(tag2)
c +="{},{},{},{}".format(list[0],list[1],list[2].replace('\n',''),tag2)
else:
tag2="無內容資訊"
c +="{},{},{},{}".format(list[0],list[1],list[2].replace('\n',''),tag2)
#print(tag2)
#寫出資料
fw=open("c.txt","w",encoding="utf8")
fw.write(c)
fw.close()
#print(c)
browser.close() #關閉 瀏覽器
print("完成")
|