新闻动态

python爬取全国水雨情信息详解

发布日期:2021-12-21 22:37 | 文章来源:CSDN

分析

我们没有找到接口,所以打算利用selenium来爬取。

代码

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()
# 存储中英文对应的变量的中文名
word_dict = {"poiBsnm": "流域",
 "poiAddv": "行政区",
 "rvnm": "河名", 
 "stnm": "站名",
 "tm": "时间", 
 "zl": "水位(米)",
 "ql": "流量(立方米/秒)",
 "wrz": "警戒水位(米)"}
# 空df接收结果
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对象
 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)
# 关闭浏览器
driver.close()
# 保存数据
data_str = datetime.datetime.now().strftime('%Y_%m_%d')
rain_total.to_csv("%s_全国水雨情信息.csv" % (data_str),index=None, encoding="GB18030")

结果

总结

时间爬取出现了一点问题,我也很不理解,其次,循环哪里应该可以简洁代码,写的不是很好,第三,没有形成模块化的代码。还有就是谢谢崔工的支持。

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注本站的更多内容!

版权声明:本站文章来源标注为YINGSOO的内容版权均为本站所有,欢迎引用、转载,请保持原文完整并注明来源及原文链接。禁止复制或仿造本网站,禁止在非www.yingsoo.com所属的服务器上建立镜像,否则将依法追究法律责任。本站部分内容来源于网友推荐、互联网收集整理而来,仅供学习参考,不代表本站立场,如有内容涉嫌侵权,请联系alex-e#qq.com处理。

相关文章

实时开通

自选配置、实时开通

免备案

全球线路精选!

全天候客户服务

7x24全年不间断在线

专属顾问服务

1对1客户咨询顾问

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部