简体   繁体   中英

Data passing from HTML text input to python script

I am creating a web scraping application, using Django, which scrapes the imdb website and lists the movie names based on what users types in the text field[suppose if user types 'b', it lists all the movie names starting with letter 'b'] I have a html text input and a button.

<body>
    <h1>The IMDB Scraper</h1>
    <form method="POST" action="">
        <input type="text" name="name" placeholder="Iron Man..">
        <input type="submit" value="Search">
    </form>
</body>

I also have a python script which scrapes the data from the website, using the hardcoded keyword.

I want to send the text input data to this python script when the button is pressed and process this data and send send the result hack to the same HTML page for display.

Yes, you can do this easily:

  • make a view that gets start parameter as JSON

Python sample:

class MyJsonForAjaxView(generic.View):

    def post(self, request, *args, **kwargs):
        if my_scrape_is_finished:
            return JsonResponse({'finished': True}, safe=False)
        return JsonResponse({'finished': False}, safe=False)
  • call that view in JavaScript (= AJAX call) with POST method:

JavaScript code:

$.ajax({
    method: 'post',
    type: 'json',
    cache: false,
    url: 'my_json_url',
    data: {"start": "Initial text from textbox"}
}).done(function(data) {
    alert('call successfull!!!');
    /* data is filled with Django result, here {'finished': value} */
    if (data.finished) {
        /* handle finished */
    } else {
        /* do a small animation to show the user something is running */
    }
    /* todo: remember the call has been made and it s registered on Django side */
}).fail(function(data) {
    alert('fatal error!');
}).always(function() {
    /* whatever the result, always do something here */
});

You can do this in the background, disable the "send" button, and ask every 3 seconds in AJAX the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM