从动态网页中刮取数据时,从选择对象中选择一个选项

2024-06-16 11:03:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一些网页抓取,我想知道如何从下拉框中选择数据并抓取它。这是页面:https://www.cbn.gov.ng/rates/ExchRateByCurrency.asp

正如您所见,这是一个动态网页,可以选择显示您想要的条目数量

Snippet of web page showing entries dropdown box which allows selection of number of entries to show

我要做的是选择最大值(100),然后从表中删除数据。你知道我该怎么做吗?以下是一些可以构建的代码:


Firefox = Firefox()
Firefox.get(source["Exchange Rates by Currency"])

sleep(30)

html = Firefox.page_source
html = bs(html,"html.parser")
table = html.find("table",id="exTable")

select_item = html.find("select")

它将带您直接进入表格并分别选择项目


Tags: 数据https网页sourcehtmlwwwtable页面
1条回答
网友
1楼 · 发布于 2024-06-16 11:03:10

使用python尝试下面的方法-requests简单、直接、可靠、快速,并且在处理请求时所需的代码更少。我在检查了谷歌chrome浏览器的网络部分后,从网站本身获取了API URL

下面的脚本到底在做什么:

  1. 首先,它将获取API URL并执行GET请求

  2. 获取数据后,脚本将使用JSON.loads库解析JSON数据

  3. 最后,它将按货币列表遍历所有汇率列表,并打印它们,例如:-买入汇率、中央汇率、货币、卖出汇率、汇率日期

    import json
    import requests
    from urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    
    def scrap_cbn_data():
    
    URL = 'https://www.cbn.gov.ng/rates/outputExchangeRateJSN.asp?_=1605068636834' #API URL
    
    response = requests.get(URL,verify=False) # GET request
    json_result = json.loads(response.text) #Parse JSON data using json.loads
    extracted_data = json_result['data'] #extracted data
    
    for item in extracted_data: #iterate over the list of exchange rate by currency
        print('-' * 100)
        print('Buying Rate : ', item['buyingrate'])
        print('Central Rate : ', item['centralrate'])
        print('Currency : ', item['currency'])
        print('Rate Date : ', item['ratedate'])
        print('Selling Rate : ', item['sellingrate'])
        print('-' * 100)
    
    scrap_cbn_data()
    

相关问题 更多 >