1. 程式人生 > 其它 >海水水質監測資訊爬取

海水水質監測資訊爬取

一、網址:url = 'http://ep.nmemc.org.cn:8888/Water/'
二、程式碼
# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : 海水水質監測資訊爬取.py
# Time       :2022/4/13 15:26
# Author     :希維
# version    :python 3.8
# Description:
"""
from fake_useragent import UserAgent
import requests
from lxml import etree

"""

"""
url 
= 'http://ep.nmemc.org.cn:8888/Water/' header = {'User-Agent': UserAgent().random} resp = requests.get(url, verify=False, headers=header) resp.encoding = 'utf-8' print(resp.status_code) e = etree.HTML(resp.text) # print(resp.text) # print(e) # print(resp.text) # -------------------------解析資料----------------------
data_head = e.xpath('//table[@id="gridHd"]/tr/td/text()') # 頭資料 li = e.xpath('//*[@id="gridDatas"]/li[1]/table/tr/td[1]/span/text()') # 主體內容資料 print(len(data_head)) with open('2021_山東.txt', 'w', encoding='Utf-8') as f: for i in data_head: f.writelines(str(i)+' ') #for i in li: # print(i) #
text = i.xpath('//*[@id="gridDatas"]/li/table/tbody/tr/td/span/text()') # print(text) print(data_head)

三、由於解析問題,直接將目標html中的ui拿出來處理

# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : ceshi.py
# Time       :2022/4/13 16:32
# Author     :希維
# version    :python 3.8
# Description:
"""
from lxml import etree

import codecs #可以不用這個
html = etree.parse('2021山東.html', etree.HTMLParser(encoding='utf-8'))
# html = etree.tostring(html, encoding='utf-8', pretty_print=True, method='html')
# html = html.decode('utf-8')

li = html.xpath('//*[@id="gridDatas"]/li')
f = codecs.open('2021_山東.txt', 'a', encoding='utf-8')
f.write('\n')
a = 0
for i in li:
    text = i.xpath('//tr/td/span/text()')
    for j in text:
        f.write(str(j)+'  ')
        a+=1
        if a%14==0:
            f.write("\n")

四、總結

  在獲取資料的過程中,資料編碼問題處理了半天(不熟悉,沒找對方向)

五、部分資料展示

海區  省份  地市  點位編碼  實測經度  實測緯度  監測時間  pH  溶解氧  化學需氧量  無機氮  活性磷酸鹽  石油類  水質類別  
渤海  山東  濱州  SDB13001  118.10  38.33  2020-11  8.28  8.93  1.15  0.200  0.006  0.018  一類  
渤海  山東  濱州  SDB13002  118.17  38.45  2020-11  8.21  8.61  1.56  0.095  0.002  0.034  一類  
渤海  山東  濱州  SDB13003  117.97  38.29  2020-11  8.26  9.61  1.38  0.103  0.004  0.031  一類  
渤海  山東  濱州  SDB13004  118.17  38.23  2020-11  8.25  8.94  1.04  0.179  0.011  0.020  一類  
渤海  山東  濱州  SDB13005  117.94  38.33  2020-11  8.27  9.29  1.40  0.100  0.003  0.035  一類  
渤海  山東  東營  SDB05001  118.64  38.23  2020-11  8.06  8.54  1.29  0.136  0.005  0.012  一類