【问题标题】:Scraping an AJAX web page using python and requests使用 python 和请求抓取 AJAX 网页
【发布时间】:2019-07-27 03:23:48
【问题描述】:

我尝试使用 beautifulsoup 查找方法抓取 this page,但在 HTML 页面中找不到表值。我发现当我通过内部 API 加载页面时,网站会立即生成数据。有什么帮助吗??

提前致谢。

【问题讨论】:

  • 我没有查看该页面,但是如果您找到了对 API 的 Ajax 请求,那么您应该能够向它发出您自己的请求?
  • 其中一个应该这样做:github.com/dhamaniasad/HeadlessBrowsers
  • @RobinZigmond 感谢您的回复。你有关于如何从 python 建立 Ajax 请求的资源吗?
  • @AhmedSabry 除了beautifulsoup 之外,您应该尝试使用Selenium,它允许您从ajax 请求中恢复数据加载,因为您可以等待加载

标签: javascript python ajax web-scraping


【解决方案1】:

这对我有用。我不得不在开发工具中四处挖掘,但找到了它

import requests

geturl=r'https://www.barchart.com/futures/quotes/CLJ19/all-futures'
apiurl=r'https://www.barchart.com/proxies/core-api/v1/quotes/get'


getheaders={

    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'cache-control': 'max-age=0',
    'upgrade-insecure-requests': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
    }

getpay={
    'page': 'all'
}

s=requests.Session()
r=s.get(geturl,params=getpay, headers=getheaders)



headers={
    'accept': 'application/json',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'referer': 'https://www.barchart.com/futures/quotes/CLJ19/all-futures?page=all',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
    'x-xsrf-token': s.cookies.get_dict()['XSRF-TOKEN']

}


payload={
    'fields': 'symbol,contractSymbol,lastPrice,priceChange,openPrice,highPrice,lowPrice,previousPrice,volume,openInterest,tradeTime,symbolCode,symbolType,hasOptions',
    'list': 'futures.contractInRoot',
    'root': 'CL',
    'meta': 'field.shortName,field.type,field.description',
    'hasOptions': 'true',
    'raw': '1'

}


r=s.get(apiurl,params=payload,headers=headers)
j=r.json()
print(j)

>{'count': 108, 'total': 108, 'data': [{'symbol': 'CLY00', 'contractSymbol': 'CLY00 (Cash)', ........

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2020-04-20
    • 2022-01-18
    • 1970-01-01
    • 2018-03-22
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多