某玩要闻数据采集详解

129 阅读2分钟

有没有发现假期之后工作明显不在状态,之前说要更一波热榜数据之后陆续有其他不错的网站插入就断层了,今天再更一个之前留好了个网站,品玩-有品好玩的科技,一切与你有关。这个网站名字名字有点长哈哈。

  1. 话不多说,直接开始,网站地址

image.png 直接进入首页,实时要闻板块可见要闻数据的列表页数据,然后抓个包看看数据接口在哪里,向下滚动翻页

image.png 可见滚动条回滚表示翻页完成

image.png 通过检索找到数据在list接口中然后具体看一下这个list接口的参数和数据格式

image.png 请求参数有两个一个是date,一个是last_id,date明显不能用作翻页翻页使用那八九不离十就是这个last_id,last在英文中标识最后,上一个的意思,盲猜这个翻页就是上一页最后一个id的下一个id是这一页的开头数据,再看返回的数据,是list的值是html。那就妥了,只需要开始之后获取到最后一个id进行下一页请求就可以了,详情页也是直接请求就可以了,数据都在html中, 2. 先请求第一个列表页然后解析出来题目和链接,并拿到最后一个id,返回给上一次请求

headers = {
    'authority': 'www.pingwest.com',
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'no-cache',
    'pragma': 'no-cache',
    'referer': 'https://www.pingwest.com/status',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest',
}
last_id = ''
next = 0
while next == 0:
    params = {
        'date': '',
        'last_id': f'{last_id}',
    }

    response = \
    requests.get('https://www.pingwest.com/api/state/list', params=params, headers=headers).json()['data']['list']
    res = etree.HTML(response)
    data_list = res.xpath("//section/section[contains(@class,'news-info')]/p[@class='title']/a")
    for data in data_list:
        title = data.xpath("./text()")[0]
        url = 'https:' + data.xpath("./@href")[0]
        last_id = url[-6:]
        print(last_id)
        print(title, url)
    print('最后一个id是',last_id)

可见代码这里用了先定义再循环再定义变量的方法实现了一个翻页 image.png 再请求详情数据还是使用gne进行解析

headers = {
    'authority': 'www.pingwest.com',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'accept-language': 'zh-CN,zh;q=0.9',
    'cache-control': 'no-cache',
    'pragma': 'no-cache',
    'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="100", "Google Chrome";v="100"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'document',
    'sec-fetch-mode': 'navigate',
    'sec-fetch-site': 'none',
    'sec-fetch-user': '?1',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36',
}

response = requests.get(url, headers=headers)

extractor = GeneralNewsExtractor()
result = extractor.extract(response.text, noise_node_list=['//div[@class="s2"]'])
print(result)

image.png ok,再稍加完善做一个是否查看详情数据的判断

image.png

VeryCapture_20230505152348.gif