作者 chickengod (雞大俠)
標題 Re: Selenium爬取資料出錯
時間 Thu Feb 11 20:20:09 2021
───────────────────────────────────────
※ 引述《code0093 (DADY)》之銘言:
: 我要爬工商名錄的資料
: 網址
: https://dmz26.moea.gov.tw/GMWeb/investigate/InvestigateFactory.aspx
: 程式碼貼在GitHub
: https://github.com/san60708/helppppppp/blob/main/ss
: 不知道為什麼我用find_elements找到資料後再用for把資料抓出來。他只會抓第一行...
: 不知道哪裡出錯了
: 請大大協助,感謝~
你需要解決網頁的彈出視窗
https://i.imgur.com/cSgaX12.jpeg
不然下一次的 driver.get() 好像會因為這樣被卡住
然後就一直死在 exception 的 while loop
以下的程式可以在遇到 alert 彈出視窗 exception 的時候按確定
from selenium.common.exceptions import UnexpectedAlertPresentException
# 此處用來取代原本的 except
except UnexpectedAlertPresentException as ex:
print("Exception has been thrown. " + str(ex))
alert = driver.switch_to.alert
alert.accept()
"""
Exception has been thrown. Alert Text: None
Message: unexpected alert open: {Alert text : 查無資料}
"""
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.25.137.58 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1613046017.A.FB6.html
※ 編輯: chickengod (114.25.137.58 臺灣), 02/12/2021 04:03:31
1F:推 code0093: 感謝大大回覆 02/12 17:32
2F:→ code0093: 我先測試某一頁,暫且忽略跳出的方塊 02/12 17:33
5F:→ code0093: 程式26行開始爬取資料 02/12 17:34
7F:→ code0093: 程式只爬得出第一行...然後這個頁面總共683筆,他就重 02/12 17:35
8F:→ code0093: 複爬683次 02/12 17:35
Hi 根據 selenium 文件
https://tinyurl.com/2de8zwvf
find_elements_by_xpath() return "WebElement" list
https://tinyurl.com/15na3djs
WebElement 是一個 class
你可以使用內建的 property 比如 .text 得到文字
data = driver.find_elements_by_xpath("//div//table[@width='90%']/tbody")
print(data[0].text)
print(data[1].text)
類似這樣
"""
工廠登記編號 630209 ...
工廠登記編號 630206 ...
"""
※ 編輯: chickengod (114.25.137.58 臺灣), 02/12/2021 23:22:04
9F:推 code0093: 感謝大大。但是我現在用for單純印出data.text是正常的 02/14 00:37
10F:→ code0093: 但是如果data.find就又是錯誤的 如圖 02/14 00:37
13F:→ code0093: 如果是webelement的話 那我要再更深入超多特定資料為什 02/14 00:39
14F:→ code0093: 麼會只印出第一筆呢..還是是我電腦問題 02/14 00:39
15F:→ code0093: 感謝大大協助 02/14 00:39
17F:推 code0093: 我換另一種方法寫就沒問題了,但是我還是很疑惑為何用fo 02/14 00:49
18F:→ code0093: r不行... 02/14 00:49
19F:→ chickengod: 我猜可能跟這個有關? 02/14 02:39
21F:→ chickengod: 會根據 xpath 寫法選擇抓整頁或者相對於元素的位置 02/14 02:39
22F:→ chickengod: 如果都是長的像絕對路徑的xpath 02/14 02:51
23F:→ chickengod: 大概就不管目前元素在哪 一律抓第一個 02/14 02:51
24F:→ chickengod: 也許就能解釋為什麼你會遇到這情況 02/14 02:51
25F:→ chickengod: 不過我是覺得以都能達到目的來說 02/14 02:51
26F:→ chickengod: 直接抓 .text 存下來 02/14 02:51
27F:→ chickengod: 再一次針對全部字串處理會不會執行比較快 02/14 02:51
28F:→ chickengod: 畢竟 selenium 還要控制一個瀏覽器 多少會影響效能 02/14 02:51
29F:推 code0093: 了解,感謝大大的用心回答 02/14 22:50
30F:→ code0093: 目前我就要先抓text下來再分解字串 效率確實快很多 02/14 22:51
31F:→ chickengod: ( ̄▽ ̄) okder ~ 02/14 23:41
32F:推 kshskghs: xpath用絕對路徑較好 03/06 13:54