1. 程式人生 > >selenium+python爬取資料跳轉網頁

selenium+python爬取資料跳轉網頁

專案要做一個四個層級欄的資料抓取,而且點選查詢後資料會在新跳出的網頁。

原始碼如下 註釋解釋

from selenium import webdriver
import selenium
#from time import sleep as sp

url='http://202.127.42.157/moazzys/nongqing.aspx'
site=webdriver.Chrome()
site.get(url)

#data={}
mainhandle=site.current_window_handle#主頁面控制代碼  每個瀏覽器標籤頁都有一個控制代碼
years=site.find_elements_by_xpath('
//select[@id="ContentPlaceHolder1_year"]/option') co_year=len(years) for d in range(co_year): years[d].click() provs=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_prov"]/option') co_prov=len(provs) for c in range(co_prov): provs[c].click() items
=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_item"]/option') co_item=len(items) for b in range(co_item): items[b].click() types=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_type"]/option') co_type=len(types)
for a in range(co_type): types[a].click() #點選進入新視窗 site.find_element_by_id('ContentPlaceHolder1_btnsearch').click() handles = site.window_handles for handle in handles:# 輪流得出標籤頁的控制代碼 切換視窗 因為只有兩個標籤頁實際是假for迴圈 if handle!=mainhandle: site.switch_to_window(handle) #獲得資料 try: raw=site.find_element_by_xpath('//tr/td[@align="right"]') print (raw.text) #data.append(raw.text) except Exception as e: print("無該資料") #獲得資料 site.close() #關閉當前標籤頁 site.switch_to_window(mainhandle)#回到原來標籤頁 types=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_type"]/option') types[a].click() items=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_item"]/option') items[b].click() provs=types=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_prov"]/option') provs[c].click() year=types=site.find_elements_by_xpath('//select[@id="ContentPlaceHolder1_year"]/option') years[d].click() site.quit()