红红火火恍恍惚惚

动态网站爬虫

2019-07-16  本文已影响0人  弘列

爬取网站:http://output.nsfc.gov.cn/projectQuery
网站特点:需要根据输入的表单信息进行检索,返回的信息在html里不直接显示,并且在翻页的时候url不变化。
这种情况就是需要我们向服务器发送请求,然后拿到数据之后,网站就会把各种数据填充到页面上,因为是通过js填充的,所以html代码里并不会出现。
比如我们需要搜的是[植物学,面上项目,结题年度2009]


在chrome里可以右键检查。数据请求都是XHR类型的。我们点到XHR,我们按检索后可以在Name中发现新的一条更新记录。
点到Response
发现就是我们需要的json文件。接下来写脚本开爬。
import requests
import json
def getProject(expert, code, projectType, ratifyYear):
    url = "http://output.nsfc.gov.cn/baseQuery/data/conclusionQueryResultsData"
    #url就是在Headers里的Request URL 
    #data就是我们需要提交的表单信息Headers里的Request Playload
    data = {
            "ratifyNo":"",
            "projectName":"",
            "personInCharge":"",
            "dependUnit":"",
            "code":"F02",  # 申请代码
            "projectType":"218", # 面上项目
            "subPType":"",
            "psPType":"",
            "keywords":"", # 项目主题词
            "ratifyYear":"2010", # 批准年度
            "conclusionYear":"", 
            "beginYear":"",
            "endYear":"",
            "checkDep":"",
            "checkType":"",
            "quickQueryInput":"",
            "adminID":"",
            "pageNum":1, # 页码,从0开始
            "pageSize":5, # 页面大小
            "queryType":"input",
            "complete":"true"
    }
    data['code'] = code
    data['personInCharge'] = expert
    data['projectType'] = projectType
    data['ratifyYear'] = ratifyYear
    payload = json.dumps(data)
    # headers就是Request Headers 我们要伪装成自己的浏览器去发送请求
    headers = {
        'origin': "http://output.nsfc.gov.cn",
        'accept-encoding': "gzip, deflate",
        'accept-language': "zh-CN,zh;q=0.9,en;q=0.8",
        'user-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
        'content-type': "application/json",
        'accept': "*/*",
        'referer': "http://output.nsfc.gov.cn/projectQuery",
        'x-requested-with': "XMLHttpRequest",
        'connection': "keep-alive",
        'cache-control': "no-cache",
        }

    response = requests.request("POST", url, data=payload, headers=headers)#发送请求并获得返回数据

    print(response.text) #打印爬下来的数据

上一篇 下一篇

猜你喜欢

热点阅读