【爬取动态网页-以黄河水文站数据为例】
生活随笔
收集整理的這篇文章主要介紹了
【爬取动态网页-以黄河水文站数据为例】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
爬取動態網頁-以黃河水文站數據為例
一、項目背景
這個項目來源于我的本科畢業設計的一部分,導師讓我去搜集這方面的數據。
二、項目過程
1、問題初探
由于我前期跟著MOOC學習了python編程語言,所以我打算用python編寫爬蟲程序來解決這個問題。但是我沒有學過爬蟲,所以我花了半天左右的時間在MOOC上學習了爬蟲的基本知識,例如requests庫和bs4庫等等。當我學完去實踐的時候發現,這個教程是針對靜態網頁的。由于我需要爬取2002年—至今每一天的數據,所以我必須知道動態頁面是怎么爬取的。我開始在網絡上搜索相關的解決辦法,下面的這篇文章給了我啟發,并進行了里面方法的嘗試。
爬蟲入門_7:動態加載數據處理及案例實戰
2、難點突破
selenium環境安裝
第一步是安裝selenium,第二步是下載對應的瀏覽器驅動程序,我下的谷歌瀏覽器的驅動程序,注意只有針對32位的驅動程序,64位的也能用,還有要下載對應的瀏覽器版本。具體操作步驟網上挺多的,這里不再贅述。
日期控件的處理
網頁上的日期是需要下拉選擇的,不能手動輸入日期,如下圖所示:
第一,我得去除日期的只讀屬性。找到標簽,并將’readonly’屬性刪除:
第二,清空原來的日期數據,輸入想要的日期數據:
browser.execute_script(js) browser.find_element(By.ID,'ContentLeft_menuDate1_TextBox11').clear()#清空原來的數據 browser.find_element(By.ID,'ContentLeft_menuDate1_TextBox11').send_keys(date[i])最后,最重要的一步。用selenium模擬點擊按鈕:
browser.find_element(By.ID,'ContentLeft_Button1').click()#模擬點擊按鈕至此,最難的一步完成了,接下來的操作就是單純針對靜態頁面的,不予贅述。
三、項目python代碼
import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium import webdriver from time import sleep from selenium.webdriver.common.by import By import bs4 import csv import datetime import time time_start=time.time()# 生成日期數據 def create_assist_date(datestart=None, dateend=None):# 創建日期輔助表if datestart is None:datestart = '2016-01-01'if dateend is None:dateend = datetime.datetime.now().strftime('%Y-%m-%d')# 轉為日期格式datestart = datetime.datetime.strptime(datestart, '%Y-%m-%d')dateend = datetime.datetime.strptime(dateend, '%Y-%m-%d')date_list = []date_list.append(datestart.strftime('%Y-%m-%d'))while datestart < dateend:# 日期疊加一天datestart += datetime.timedelta(days=+1)# 日期轉字符串存入列表date_list.append(datestart.strftime('%Y-%m-%d'))return date_listif __name__ == '__main__':date = create_assist_date("2002-01-01", '2002-12-31') for i in range(len(date)):# 設置selenium使用chrome的無頭模式chrome_options = Options()chrome_options.add_argument('--headless')chrome_options.add_argument('--disable-gpu')# 在啟動瀏覽器時加入配置browser = webdriver.Chrome(options=chrome_options)# 模擬瀏覽器打開網址browser.get('http://61.163.88.227:8006/hwsq.aspx?sr=0nkRxv6s9CTRMlwRgmfFF6jTpJPtAv87')# 等待加載,最多等待20秒js='document.getElementById("ContentLeft_menuDate1_TextBox11").removeAttribute("readonly");'browser.execute_script(js)browser.find_element(By.ID,'ContentLeft_menuDate1_TextBox11').clear()#清空原來的數據browser.find_element(By.ID,'ContentLeft_menuDate1_TextBox11').send_keys(date[i])browser.find_element(By.ID,'ContentLeft_Button1').click()#模擬點擊按鈕sleep(2)html=browser.page_sourcesoup=BeautifulSoup(html,'html.parser')data=soup.find_all('table','mainTxt')f = open('data2002.csv', 'a+', newline="", encoding='utf-8')writer = csv.writer(f)for tr in data[1]('tbody')[0].children:#注意因為data[1]('tbody')是列表,必須加上[0]if isinstance(tr,bs4.element.Tag):tds=tr('td')writer.writerow([date[i],tds[0].string,tds[1].string,tds[2].string,tds[3].string,tds[4].string])for tr in data[2]('tbody')[0].children:#注意因為data[2]('tbody')是列表,必須加上[0]if isinstance(tr,bs4.element.Tag):tds=tr('td')writer.writerow([date[i],tds[0].string,tds[1].string,tds[2].string,tds[3].string,tds[4].string])f.close() time_end=time.time() print('共運行{}s'.format(time_end-time_start))總結
以上是生活随笔為你收集整理的【爬取动态网页-以黄河水文站数据为例】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android+多米音乐+自动播放,an
- 下一篇: 电视卡众说纷纭(三):软压卡硬压卡区别