Mohammad Chenarani
Mohammad Chenarani

Reputation: 113

How To Get Result Of A HTML Page With Python

edit : SORRY THIS IS COMPLETELY WRONG! thanks for answers <3

hello i want to get result of my html page my url is here : http://Xantia.rzb.IR/PG/IP result of this page is client ip but in source i have :

<script>function getIP(json) {document.write(json.ip);}</script>
<script src="http://api.ipify.org?format=jsonp&callback=getIP"></script>

<script>function getIP(json) {document.write(json.ip);}</script>
<script src="http://api.ipify.org?format=jsonp&callback=getIP"></script>

and when i use requests.get('http://xantia/pg/ip').text i just get above source Is there a way to get the result of this URL? I have a weblog and I want to make an API for getting pubic IP if can I use PHP or Django pls help because I just have python I'm sorry because my English is very bad

Upvotes: 0

Views: 946

Answers (2)

user3190433
user3190433

Reputation: 405

Your question is very vague. What exactly do you want to achieve?

The request delivers exactly what you request - the source code of http://xantia/pg/ip. JavaScript is executed on client (in browser, after the response is received) and not on server (before the response is generated).

What you want to achieve exactly? Receive the public ip address of the server or the ip address of visitor of your page?

For the visitors address you can use in your server side php:

<?php

$ip = $_SERVER['REMOTE_ADDRESS'];
echo $ip;

If you want to receive your servers public address, you can do something like in your server side php:

<?php

$response = file_get_contents('http://api.ipify.org/?format=json');
$data = json_decode($response, true);
$ip = $data['ip'];
echo $ip;

Please note that this is just a simple example (which requires that allow_url_fopen is enabled in your php.ini). Better is to use a http client library (https://packagist.org/?query=http%20client).

You should also handle exceptions - what happens if api.ipfy.org is not reachable? If this request is made everytime your page is requested, it will slow down the response time of your server. In this case you should cache the IP somewhere - i guess the public server address will not change very often (except you are using a dynamic dns service).

Upvotes: 3

Igor Ilic
Igor Ilic

Reputation: 1368

From the ipify.org own sample code on the homepage, there is a block of code showing how to get the IP value in python:

# This example requires the requests library be installed.  You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/

from requests import get

ip = get('https://api.ipify.org').text

print('My public IP address is: {}'.format(ip))

Upvotes: 3

Related Questions