我在一个MySQL表中有大约6600万个域,我需要在所有域上运行爬虫,并在爬虫完成时更新行计数=1。
爬虫脚本在php中,使用php爬虫库,这里是脚本。
set_time_limit(10000);
try{
$strWebURL = $_POST['url'];
$crawler = new MyCrawler();
$crawler->setURL($strWebURL);
$crawler->addContentTypeReceiveRule("#text/html#");
$crawler->addURLFilterRule("#\.(jpg|jpeg|gif|png)$# i");
$crawler->enableCookieHandling(true);
$crawler->setTrafficLimit(1000 * 1024);
$crawler->setConnectionTimeout(10);
//start of the table
echo '<table border="1" style="margin-bottom:10px;width:100% !important;">';
echo '<tr>';
echo '<th>URL</th>';
echo '<th>Status</th>';
echo '<th>Size (bytes)</th>';
echo '<th>Page</th>';
echo '</tr>';
$crawler->go();
echo '</table>';
$this->load->model('urls');
$this->urls->incrementCount($_POST['id'],'urls');
}catch(Exception $e){
}$this->urls>增量计数();只更新行并标记计数列=1
因为我有6600万个域,我需要在我的服务器上运行一个cron作业,而当cronjob在命令行上运行时,我需要一个无头浏览器,所以我选择了phanjomjs,因为爬行器不像我希望的那样工作,没有无头浏览器(幻影)。
我面临的第一个问题是从mysql db加载域,然后从js脚本运行爬虫脚本--我尝试过这样做:
这是代码
import MySQLdb
import httplib
import sys
import subprocess
import json
args = sys.argv;
db = MySQLdb.connect("HOST","USER","PW","DB")
cursor = db.cursor()
#tablecount = args[1]
frm = args[1]
limit = args[2]
try:
sql = "SELECT * FROM urls WHERE count = 0 LIMIT %s,%s" % (frm,limit)
cursor.execute(sql)
print "TOTAL RECORDS: "+str(cursor.rowcount)
results = cursor.fetchall()
count = 0;
for row in results:
try:
domain = row[1].lower()
idd = row[0]
command = "/home/wasif/public_html/phantomjs /home/wasif/public_html/crawler2.js %s %s" % (domain,idd)
print command
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
print script_response
except:
print "error running crawler: "+domain
except:
print "Error: unable to fetch data"
db.close()它需要两个参数来设置从数据库中选择域的限制。
预先处理域并使用子流程运行此命令。
command = "/home/wasif/public_html/phantomjs /home/wasif/public_html/crawler2.js %s %s" % (domain,idd)
command
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
print script_responseis文件还包含2个args,1个是域,第二个是更新计数=1的id,当爬虫完成时,这是爬虫2.js。
var args = require('system').args;
var address = '';
var id = '';
args.forEach(function(arg, i) {
if(i == 1){
address = arg;
}
if(i == 2){
id = arg;
}
});
address = "http://www."+address;
var page = require('webpage').create(),
server = 'http://www.EXAMPLE.net/main/crawler',
data = 'url='+address+'&id='+id;
console.log(data);
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log(address+' Unable to post!');
} else {
console.log(address+' : done');
}
phantom.exit();
});它运行得很好,但是我的脚本在某个时候之后就被卡住了,需要在某个时候重新启动,而日志显示没有什么问题。
我需要优化这个过程,并尽可能快地运行爬虫,任何帮助都将不胜感激。
发布于 2015-03-01 09:06:25
网络爬虫程序员在这里。:)
您的蟒蛇依次执行幻影。你应该并行做。要做到这一点,执行幻影,然后离开它,不要等待它。
在PHP中,如下所示:
exec("/your_executable_path > /dev/null &");如果你不需要的话就不要用幻影。它渲染了一切。需要>50 be内存。
https://stackoverflow.com/questions/28791657
复制相似问题