1、安装Eclipse
先安装jdk,再安装Eclipse,成功后开始建立py_java项目,在这个项目的存储目录SRC下建立test包,在test包中New-Class,新建MyDemo类,建好完成后就可以在MyDemo中写代码了
2、python脚本内容
import numpy as np
from selenium import webdriver def main():
url = 'https://www.tianyancha.com/login'
driver = webdriver.Chrome()
driver.get(url)
if __name__ == '__main__':
a = np.ones(3)
print(a)
print('java 调用有第三方库的python脚本成功')
main()
调用了两个三方库,有输出操作和打开浏览器操作
3、MyDemo类的代码(java调用python脚本)
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MyDemo { public static void main(String[] args) {
try {
System.out.println("start");
String[] args1=new String[]{"python","D:\\pyworkpeace\\9_30_1.py"};
Process pr=Runtime.getRuntime().exec(args1); BufferedReader in = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("end");
} catch (Exception e) {
e.printStackTrace();
}}
public void test(){
System.out.println("我的第一个方法C");
} }
4、运行结果如下所示
不光有打印窗口,而且还弹出了天眼查的浏览器,程序完成后浏览器也就关闭了
5、java动态传递参数
这次要做的是通过java传递url给python脚本,而python脚本用浏览器打开接收到的url网页。
(1)首先定义一个url参数在java中 ;String url="http://blog.csdn.net/thorny_v/article/details/61417386";
(2)将参数传递给python; String[] args1 = new String[] { "python", "D:\\pyworkpeace\\9_30.py", url};
java中其他地方完全一样 没有改动
(3)python中需要做一点小变动,重写了一下代码
import sys
from selenium import webdriver def main(a):
driver = webdriver.Chrome() # 打开浏览器
driver.get(a) # 浏览器打开指定页面
if __name__ == '__main__':
for i in range(1, len(sys.argv)):
url = sys.argv[i]
main(url)
其中需要注意的是接收参数从sys.argv[1]开始,sys.argv[0]是python脚本的参数地址,没什么用。最后就大功告成了
//这个程序可以调用python脚本,并向python脚本中传递参数 package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test_1 { public static void main(String[] args) {
try {
//String a=getPara("car").substring(1),b="D34567",c="LJeff34",d="iqngfao";
//String[] args1=new String[]{ "python", "D:\\pyworkpeace\\9_30_1.py", a, b, c, d };
//Process pr=Runtime.getRuntime().exec(args1);
String url="http://blog.csdn.net/thorny_v/article/details/61417386";
System.out.println("start;"+url);
String[] args1 = new String[] { "python", "D:\\pyworkpeace\\9_30.py", url};
Process pr=Runtime.getRuntime().exec(args1);
BufferedReader in = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("end");
}
catch (Exception e) {
e.printStackTrace();
}
}
private static String getPara(String string) {
// TODO Auto-generated method stub
return null;
} }