python爬取全國(guó)水雨情信息詳解
發(fā)布日期:2021-12-21 22:37 | 文章來(lái)源:CSDN

分析
我們沒(méi)有找到接口,所以打算利用selenium來(lái)爬取。
代碼
import datetime
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options #建議使用谷歌瀏覽器
import time
chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome()
# 存儲(chǔ)中英文對(duì)應(yīng)的變量的中文名
word_dict = {"poiBsnm": "流域",
"poiAddv": "行政區(qū)",
"rvnm": "河名",
"stnm": "站名",
"tm": "時(shí)間",
"zl": "水位(米)",
"ql": "流量(立方米/秒)",
"wrz": "警戒水位(米)"}
# 空df接收結(jié)果
rain_total = pd.DataFrame([])
url = 'http://xxfb.mwr.cn/sq_dxsk.html'
driver.get(url)
time.sleep(5)
infos = driver.find_elements_by_xpath("/html/body//tbody[@id='DataContainer']/tr")
# pd.set_option('display.max_columns', None)#所有列
# pd.set_option('display.max_rows', None)#所有行
# 列表提取
for info in infos:
poiBsnm = info.find_element_by_xpath("./td[1]").text
poiAddv = info.find_element_by_xpath("./td[2]").text
rvnm = info.find_element_by_xpath("./td[3]").text
stnm = info.find_element_by_xpath("./td[4]").text
tm = info.find_element_by_xpath("./td[5]").text
zl = info.find_element_by_xpath("./td[6]").text
ql = info.find_element_by_xpath("./td[7]").text
wrz = info.find_element_by_xpath("./td[8]").text
# 組成pandas對(duì)象
rain_data = [[poiBsnm,poiAddv,rvnm,stnm,tm,zl,ql,wrz]]
rain_df = pd.DataFrame(data=rain_data,columns=list(word_dict.values()))
rain_total = pd.concat([rain_total,rain_df])
print(rain_total)
# 關(guān)閉瀏覽器
driver.close()
# 保存數(shù)據(jù)
data_str = datetime.datetime.now().strftime('%Y_%m_%d')
rain_total.to_csv("%s_全國(guó)水雨情信息.csv" % (data_str),index=None, encoding="GB18030")
結(jié)果

總結(jié)
時(shí)間爬取出現(xiàn)了一點(diǎn)問(wèn)題,我也很不理解,其次,循環(huán)哪里應(yīng)該可以簡(jiǎn)潔代碼,寫(xiě)的不是很好,第三,沒(méi)有形成模塊化的代碼。還有就是謝謝崔工的支持。
本篇文章就到這里了,希望能夠給你帶來(lái)幫助,也希望您能夠多多關(guān)注本站的更多內(nèi)容!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信