Python study notes-use Chaquopy to call Python libraries in AndroidStudio

introduction

Following the previous article, this article will try to introduce the python library and call the method.
(Previous: Python study notes-use Chaquopy to add Python environment in AndroidStudio, java and python intermodulation )
The python library supported by Chaquopy can be found in this link: https://chaquo.com/pypi-2.1/

Continue to add calls to the python library

As shown in the build.gradle in the app directory, add the pip command to the python structure added earlier.
The install library needs to be in the library supported by Chaquopy. Unsupported libraries will cause errors when running.
Insert picture description here
Then create a new callPyLib.py file in the python directory, the
Insert picture description here
code is as follows, crawler + numpy call, and also draw a ❤

from bs4 import BeautifulSoup
import requests
import numpy as np

# 爬取网页并解析
def get_http():
    requests.packages.urllib3.disable_warnings()
    r = requests.get("https://www.baidu.com/",verify=False)
    r.encoding ='utf-8'
    bsObj = BeautifulSoup(r.text,"html.parser")
    for node in bsObj.findAll("a"):
        print("---**--- ", node.text)

# 使用numpy
def print_numpy():
    y = np.zeros((5,), dtype = np.int)
    print(y)

def Love():
    print('\n'.join([''.join([(''[(x-y) % len('wwb_nb')] if ((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3 <= 0else' ') for x in range(-30, 30)]) for y in range(30, -30, -1)]))

Then add the calling method in MainActivity

void callPythonCodeFromLib(){
    
    
        Python py = Python.getInstance();
        py.getModule("callPyLib").callAttr("get_http");
        py.getModule("callPyLib").callAttr("print_numpy");
        py.getModule("callPyLib").callAttr("Love");
    }

Invoke the method in onCreate.
Insert picture description here
Network permissions are also required to crawl webpages. Add network permissions in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

After connecting to the mobile phone, running, you can see the print result in logcat
(If the android studio emulator is connected to the Internet, you need to set up the emulator. Go to Baidu for this)

Print the array:
Insert picture description here

Print website crawling:
Insert picture description here

Print ❤ Hahahaha The
Insert picture description here
whole project: https://download.csdn.net/download/wwb1990/12120537

Above~

Guess you like

Origin blog.csdn.net/wwb1990/article/details/104053465