Web scraping an “onclick” object table on a website with python

后端 未结 2 1151
逝去的感伤
逝去的感伤 2021-01-28 17:29

I am trying to scrape the data for this link: page.

If you click the up arrow you will notice the highlighted days in the month sections. Clicking on a highlighted day,

2条回答
  •  [愿得一人]
    2021-01-28 18:12

    Well, i see there's no reason to use selenium for such case as it's will slow down your task.

    The website is loaded with JavaScript event which render it's data dynamically once the page loads.

    requests library will not be able to render JavaScript on the fly. so you can use selenium or requests_html. and indeed there's a lot of modules which can do that.

    Now, we do have another option on the table, to track from where the data is rendered. I were able to locate the XHR request which is used to retrieve the data from the back-end API and render it to the users side.

    You can get the XHR request by open Developer-Tools and check Network and check XHR/JS requests made depending of the type of call such as fetch

    import requests
    import json
    
    data = {
        'from': '2020-1-01',
        'to': '2020-3-01'
    }
    
    
    def main(url):
        r = requests.post(url, data=data).json()
        print(json.dumps(r, indent=4)) # to see it in nice format.
        print(r.keys())
    
    
    main("http://www.ibex.bg/ajax/tenders_ajax.php")
    

    Because am just a lazy coder: I will do it in this way:

    import requests
    import re
    import pandas as pd
    import ast
    from datetime import datetime
    
    data = {
        'from': '2020-1-01',
        'to': '2020-3-01'
    }
    
    
    def main(url):
        r = requests.post(url, data=data).json()
        matches = set(re.findall(r"tender_date': '([^']*)'", str(r)))
        sort = (sorted(matches, key=lambda k: datetime.strptime(k, '%d.%m.%Y')))
        print(f"Available Dates: {sort}")
        opa = re.findall(r"({\'id.*?})", str(r))
        convert = [ast.literal_eval(x) for x in opa]
        df = pd.DataFrame(convert)
        print(df)
        df.to_csv("data.csv", index=False)
    
    
    main("http://www.ibex.bg/ajax/tenders_ajax.php")
    

    Output: view-online

提交回复
热议问题