dq62957 2018-05-25 21:13
浏览 43

如何在php的后台运行python web scraper

I have been trying to figure out how to run a python web scraper from a PHP interface. The web scraper puts data into a mysql database, and the PHP interface echos the data in a table. I have spent a lot of time researching this, however the data never shows up in the table, even when I keep the data in the database, and reload the interface, no data shows up. Also When i call the python script in the terminal and then open the interface, the data arrives. Is there any way people could recommend doing this? the first php script is as follows:

<!DOCTYPE HTML>
<html>
<body>
<?php
echo "3h test";
exec("python 3h.py");
?>
<form>
<input type="button" value="ViewCode" onclick="location="'python 3h.py'>
</form> 
<a href="action.php">Run script.</a>
</body>
</html>

the python crawler is:

from urllib import urlopen
from bs4 import BeautifulSoup
import pymysql.cursors

# Webpage connection
page1 = urlopen("http://www.officialcharts.com/charts/singles-    chart/19800203/7501/")
page2= urlopen("http://www.officialcharts.com/charts/")
# Grab title-artist classes and store in recordList
bsObj0 = BeautifulSoup(page1,"html.parser")
bsObj1 = BeautifulSoup(page2,"html.parser")

recordList0 = bsObj0.findAll("div", {"class" : "title-artist",})

recordList = recordList0 + bsObj1.findAll("div", {"class" : "title-artist",})
connection = pymysql.connect(host='localhost',
                         user='root',
                         password='******',
                         db='crawler database',
                         charset='utf8mb4',
                         cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        for record in recordList:
            title = record.find("div", {"class": "title",}).get_text().strip()
            artist = record.find("div", {"class": "artist"}).get_text().strip()
            sql = "INSERT INTO `mytable` (`title`,`artist`) VALUES (%s,%s)"
            cursor.execute(sql,(artist,title))
    connection.commit()
finally:
    connection.close()

the python script is named 3h.py

the final php script is to long for me to bother typing out, this is the core:

 <?php
 $no     = 1;
 $total  = 0;
 while ($row = mysqli_fetch_array($query))
 {
 echo '<tr>
 <td>'.$no.'</td>
 <td>'.$row['itemName'].'</td>
 <td>'.$row['itemCost'].'</td>
 </tr>';
 $no++;
 }?>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值