工作中涉及到了内容抓取的需求,用 Python 根据Url抓取对应的Html页面,并存储到本地文件,然后程序内继续将本地文件的路径作为参数,调用Node进行杂质过滤和内容提取。但怪的是在Python执行期间,已经完成了write操作,Node读取该文件的时候却得不到任何内容!这让我很尴尬
复现情景
伪代码如下
# filename: spider.py
# 要写入的html路径html_file_path = 'xxx.html'
# request进行抓取response = requests.get(url)
content = response.content
# 进行文件写入html_handler = open(html_file_path, "w")
html_handler.write(content) # 注意这里完成了write操作
# 调用Node进行内容过滤,Node会读取刚刚写入的 Html 文件shell = 'node filter.js --input ' + html_file_path
# 执行shell命令process = subprocess.Popen(shell)
process.communicate()
其中filter.js中是这么读取输入文件的:
filename = 'xxx.html'
var sourceContent = fs.readFileSync(filename, {
encoding: 'utf8'
});
console.log(sourceContent);
...
开始执行
pyth