Calling back-end API of CNBC in python

耗尽温柔 提交于 2020-05-16 03:12:10

问题


As a followup to this question, how can I locate the XHR request which is used to retrieve the data from the back-end API on CNBC News in order to be able to scrape this CNBC search query?

The end goal is to have a doc with: headline, date, full article and url.

I have found this: https://api.sail-personalize.com/v1/personalize/initialize?pageviews=1&isMobile=0&query=coronavirus&qsearchterm=coronavirus

Which tells me I don't have access. Is there a way to access information anyway?


回答1:


Actually my previous answer for you were addressing your question regarding the XHR request:

But here we go with a screenshot:

import requests

params = {
    "queryly_key": "31a35d40a9a64ab3",
    "query": "coronavirus",
    "endindex": "0",
    "batchsize": "100",
    "callback": "",
    "showfaceted": "true",
    "timezoneoffset": "-120",
    "facetedfields": "formats",
    "facetedkey": "formats|",
    "facetedvalue":
    "!Press Release|",
    "needtoptickers": "1",
    "additionalindexes": "4cd6f71fbf22424d,937d600b0d0d4e23,3bfbe40caee7443e,626fdfcd96444f28"
}

goal = ["cn:title", "_pubDate", "cn:liveURL", "description"]


def main(url):
    with requests.Session() as req:
        for page, item in enumerate(range(0, 1100, 100)):
            print(f"Extracting Page# {page +1}")
            params["endindex"] = item
            r = req.get(url, params=params).json()
            for loop in r['results']:
                print([loop[x] for x in goal])


main("https://api.queryly.com/cnbc/json.aspx")

Pandas DataFrame version:

import requests
import pandas as pd

params = {
    "queryly_key": "31a35d40a9a64ab3",
    "query": "coronavirus",
    "endindex": "0",
    "batchsize": "100",
    "callback": "",
    "showfaceted": "true",
    "timezoneoffset": "-120",
    "facetedfields": "formats",
    "facetedkey": "formats|",
    "facetedvalue":
    "!Press Release|",
    "needtoptickers": "1",
    "additionalindexes": "4cd6f71fbf22424d,937d600b0d0d4e23,3bfbe40caee7443e,626fdfcd96444f28"
}

goal = ["cn:title", "_pubDate", "cn:liveURL", "description"]


def main(url):
    with requests.Session() as req:
        allin = []
        for page, item in enumerate(range(0, 1100, 100)):
            print(f"Extracting Page# {page +1}")
            params["endindex"] = item
            r = req.get(url, params=params).json()
            for loop in r['results']:
                allin.append([loop[x] for x in goal])
        new = pd.DataFrame(
            allin, columns=["Title", "Date", "Url", "Description"])
        new.to_csv("data.csv", index=False)


main("https://api.queryly.com/cnbc/json.aspx")

Output: view online



来源:https://stackoverflow.com/questions/61154530/calling-back-end-api-of-cnbc-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!