网页爬虫 - python:爬取带有下拉框日期的数据?
高洛峰
高洛峰 2017-04-17 17:33:12
0
3
2083

需要用到这方面的数据,单独一页一页的复制了一段时间的数据,发现很是耗时,想从深圳市环保局下载空气质量历史数据。选择日期后,页面出现一个相应的数据表格,每天有24个时间点的。需要将每一天每一个小时的数据都爬下来。页面如下:
网址:http://www.szhec.gov.cn/pages/szepb/kqzl...

麻烦大家

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(3)
黄舟

使用requests.post請求


上圖的URL


hash值在上圖的位置。

圖中是response

#coding=utf-8
import requests
from bs4 import BeautifulSoup

get_url="http://www.szhec.gov.cn/pages/szepb/kqzl/TGzfwHjKqzlzs.jsp?FLAG=FIRSTFW"#取得hash值
post_url="http://www. szhec.gov.cn/pages/szepb/kqzl/TGzfwHjKqzlzs.jsp" #取得空氣品質時報
html=requests.get(get_url)
#使用beautiful網頁,取得hash值解析。 html_soup=BeautifulSoup(html.text,"html.parser")
hash=html_soup.select("input[name=hash]")
hash=hash[0].get('value')
#建構data
data={

'hash':hash,
'FROM_SELF':'true',
'q_JCRQ':'2016-04-01',
'q_SDATE':'00',
'q_JCDW':'',
'q_JCDW_text':'',
}

#至此已經正確獲取了控製品質時報的資訊
tqHtml=requests.post(post_url,data=data)
print tqHtml.text#🎜#text#🎜#

刘奇

右鍵檢查元素,查看 network,選擇一個時間搜索,查看調用的 ajax API 地址:

PHPzhong

接上:
我大概用了這段程式碼試了下,程式既不報錯也沒有結果。請問錯在哪裡?
import requests
import xlwt
from bs4 import BeautifulSoup
import datetime
import tqqqqpq;

def datelist(start, end):

start_date = datetime.datetime(*start)
end_date = datetime.datetime(*end)
result = []
curr_date = start_date
while curr_date != end_date:
    result.append("%04d-%02d-%02d-%02d" % (curr_date.year, curr_date.month, curr_date.day,curr_date.hour))
return result
def get_html():

global h
s = requests.session()
url = 'http://www.szhec.gov.cn/pages/szepb/kqzl/TGzfwHjKqzlzs.jsp'
headers = {
    'User-Agent':'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; ja-jp) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7',
    'Referer':'http://www.szhec.gov.cn/pages/szepb/kqzl/TGzfwHjKqzlzs.jsp',
    'Host':'www.szhec.gov.cn',
    'Cookie':'JSESSIONID=1F7389E70413F613C3A166D8F5A963C4',
    'Connection':'keep-alive',
    'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding':'gzip, deflate',
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
}

r = s.post(url, data=dt, headers=headers)
h = r.content.decode('utf-8')
def get_excel():

book = xlwt.Workbook(encoding = 'utf-8',style_compression=0)
sheet = book.add_sheet('data',cell_overwrite_ok = True)

global dt
j = 0
for each in datelist((2016, 3, 1,0), (2016, 3, 31,23)):
    dt = {'cdateEnd':each,'pageNo1':'1','pageNo2':''}
    get_html()
    soup = BeautifulSoup(h, "html.parser")
    #j = 0
    for tabb in soup.find_all('tr'):
        i=0;
        for tdd in tabb.find_all('td'):
            #print (tdd.get_text()+",",)
            sheet.write(j,i,tdd.get_text())
            i = i+1
        j=j+1
book.save(r'.\re'+each+'.xls')
get_excel()

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!