我必须实现一个Web抓取工具,并且选择使用带有react和python的电子js。
我可以按照以下方式在电子中使用integrate进行蟒蛇和反应,
反应码
import React from 'react';
var path = require("path")
const {PythonShell} = require("python-shell");
const city = 'XYZ';
var options = {
scriptPath : path.join(__dirname, '../../python/'),
args : [city]
}
class App extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
var shell = new PythonShell('main.py', options); //executes python script on python3
shell.on('message', function(message) {
console.log('message', message)
})
}
render (){
return (
<div className="header">
<h1>Hello, World, {this.state.test}</h1>
</div>
)
}
}
export default App;
Python代码
import sys
import requests
from bs4 import BeautifulSoup
from queue import Queue, Empty
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urljoin, urlparse
city = sys.argv[1]
class MultiThreadScraper:
def __init__(self, base_url):
self.base_url = base_url
self.root_url = '{}://{}'.format(urlparse(self.base_url).scheme, urlparse(self.base_url).netloc)
self.pool = ThreadPoolExecutor(max_workers=5)
self.scraped_pages = set([])
self.to_crawl = Queue()
self.to_crawl.put(self.base_url)
def parse_links(self, html):
soup = BeautifulSoup(html, 'html.parser')
links = soup.find_all('a', href=True)
for link in links:
url = link['href']
if url.startswith('/') or url.startswith(self.root_url):
url = urljoin(self.root_url, url)
if url not in self.scraped_pages:
self.to_crawl.put(url)
def scrape_info(self, html):
return
def post_scrape_callback(self, res):
result = res.result()
if result and result.status_code == 200:
self.parse_links(result.text)
self.scrape_info(result.text)
def scrape_page(self, url):
try:
res = requests.get(url, timeout=(3, 30))
return res
except requests.RequestException:
return
def run_scraper(self):
while True:
try:
target_url = self.to_crawl.get(timeout=60)
if target_url not in self.scraped_pages:
print("Scraping URL: {}".format(target_url))
self.scraped_pages.add(target_url)
job = self.pool.submit(self.scrape_page, target_url)
job.add_done_callback(self.post_scrape_callback)
except Empty:
return
except Exception as e:
print(e)
continue
if __name__ == '__main__':
s = MultiThreadScraper("http://websosite.com")
s.run_scraper()
在React中执行python shell之后,我可以获得所有报废的URL,但是我希望在React前端中实时获取所有URL。
以下React代码执行python代码并给出最终结果
var shell = new PythonShell('main.py', options); //executes python script on python3
此React代码用于通过简单的'print'语句从python脚本接收消息。
pyshell.on('message', function (message) {
console.log(message);
});
执行python代码时,有什么方法可以实时获取结果?