Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement simple ip extraction function with python3

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "python3 how to achieve simple ip extraction function", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "python3 how to achieve simple ip extraction function" bar!

Prepare the environment python3,win10 system. Of course, linux is better. You need to install the reuqests module under win (you need to initiate a request to call a third-party API to query the ip attribution)

\ Users\ Desktop > pip install requestsCollecting requests Downloading requests-.-py2.py3-none-any.whl (kB)% kB kB/sCollecting chardet=. (from requests) Downloading chardet-.-py2.py3-none-any.whl (kB)% kB kB/sCollecting idna= (from requests) Downloading idna--py2.py3-none-any.whl (kB)% kB MB/sCollecting urllib3=. (from requests) Downloading urllib3--py2.py3-none-any.whl (kB)% kB kB/sCollecting certifi > =. (from requests) Downloading certifi-.-py2.py3-none-any.whl (kB)% kB MB/sInstalling collected chardet, idna, urllib3, certifi, requestsSuccessfully installed certifi-. Chardet-. Idna- requests-. Urllib3-

Here, I call Ali's third-party API to query the IP attribution place, and the API address is http://ip.taobao.com/instructions.php.

Interface description 1. Request API (GET): / service/getIpInfo.php?ip= [ip address string] 2. Response information: (json format) country, province (autonomous region or municipality directly under the Central Government), city (county), operator 3. Return data format: {: 0Magne: {:,:} where the value of code means 0: success, 1: failure.

Here is a general introduction to ideas, reading files, defining functions, looping, initiating requests, receiving parameters, judging, filtering and writing to files, and completion.

To run the python file, write the header file format first, tell the system to run the python3 code, and encode it in utf-8

#! usr/bin/python3

#-*-coding:utf-8-*-

Requests requests requests URL = + ip r = requests.get (, timeout=) print () ip = checkip (ip)

The result of running the code is as follows, and the preliminary judgment of the code should be fine.

C:\ Users\ 92039\ Desktop > python 2.py

Test

Requests URL = + ip r = requests.get (, timeout=) print () ip = checkip (ip) requests URL = + ip r = requests.get (, timeout=) json_data = r.json () region = json_data [] print () ip = checkip (ip)

Region = json_ data [u 'data'] [upright region']

The code here is written in the format of the json returned by the interface.

Requests URL = + ip r = requests.get (, timeout=) json_data = r.json () region = json_data [] [] print (region) ip = checkip (ip)

C:\ Users\ 92039\ Desktop > python 2.py

Shanxi province

The test succeeded

Even if the syntax of the Python program is correct, errors can occur when running it. Errors detected at run time are called exceptions. Most exceptions are not handled by the program, but are presented in the form of errors

Exception handling should be carried out at this time.

Introduction of try/except

X = / ZeroDivisionError err: print (, err) yichang ()

C:\ Users\ 92039\ Desktop > python 5.py

Exception: division by zero

If there is no exception handling, the error will be reported directly, resulting in the program unable to continue the execution department.

Requests: URL = + ip r = requests.get (URL,timeout=) json_data = r.json () region = json_data [] [] print (region): ip = checkip (ip)

C:\ Users\ 92039\ Desktop > python 2.py

Shanxi province

Next, add if judgment.

Requests: URL = + ip r = requests.get (URL,timeout=) json_data = r.json () region = json_data [] [] region = =:: ip = checkip (ip)

Then you need to add the code that opens the file.

When processing as a file, you need to get a file handle, read data from the file, and then close the file handle.

File = open () data = file.read () file.close ()

There are two questions. First, you may forget to close the file handle; second, there is an exception in reading data from the file without any processing.

However, with can handle exceptions generated by the context very well.

= f.read ()

Open () f: ips = f.read () .split () ip ips: print (ip)

Three ip are written in ips.txt

222.31.41.253 # Shanxi 202.12.15.52 # Japan 61.135.169.12 # Beijing

Running result

C:\ Users\ 92039\ Desktop > python 3.py

222.31.41.253

202.12.15.52

61.135.169.121

Add the module to the code

Requests: URL = + ip r = requests.get (URL,timeout=) json_data = r.json () region = json_data [] [] region = =: print (ip):: open () f: ips = f.read () .split () ip ips: print (ip) checkip (ip)

C:\ Users\ 92039\ Desktop > python 2.py

222.31.41.253

222.31.41.253

202.12.15.52

61.135.169.121

Because there are two outputs, the ip belonging to Shanxi Province will be printed twice. From the running results, only the first ip belongs to Shanxi Province.

Next, you need to add a module to write files, and write all the ip belonging to Shanxi Province to one file.

Open (,) fw: I range (): fw.write () original data 1234

After running the script

one

two

three

four

A

A

A

A

A

Supplement the knowledge of file operation. File opening mode.

R, read-only mode [default mode, file must exist, exception is thrown if it does not exist]

W, write-only mode [unreadable; created if it does not exist; empty if it exists]

X, write-only mode [unreadable; created if it does not exist, error reported if it exists]

A, append mode [readable; create if it does not exist; only append content if it exists], and the file pointer is automatically moved to the end of the file.

"+" means that you can read and write a file at the same time.

Read / write [readable, writable]

Write, read [read, write], erase the contents of the file, and then open the file in read-write mode.

X +, write and read [readable, writable]

Write, read [read, write], open the file in read-write mode, and move the file pointer to the end of the file.

"b" means to operate in bytes and open the file in binary mode, not in text mode.

Rb or rudb

Wb or Whiteb

Xb or Whiteb

Ab or astatb

Note: when opened in b mode, the content read is of byte type, and the byte type also needs to be provided when writing, so the encoding cannot be specified.

Add 2 lines of code written to the file

Requests: URL = + ip r = requests.get (URL,timeout=) json_data = r.json () region = json_data [] [] region = =: open (,) fw: fw.write (+ ip):: open () f: ips = f.read (). Split () ip ips: checkip (ip)

Run the script

:\\ 92039\ > 2

An a.txt document is created on the desktop, and the result is

222.31.41.253

Thank you for reading, the above is "python3 how to achieve simple ip extraction function" of the content, after the study of this article, I believe you on python3 how to achieve a simple ip extraction function of this problem has a deeper understanding, the specific use of the need for you to practice and verify. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report