在Ubuntu下部署Python爬虫,可以按照以下步骤进行:
sudo apt update
sudo apt install python3 python3-pip
python3 -m venv myenv
source myenv/bin/activate
pip install requests beautifulsoup4 lxml
pip install selenium
并且需要下载并安装与Chrome浏览器版本匹配的chromedriver。创建一个新的Python文件,例如my_spider.py
,并编写爬虫逻辑。例如:
import requests
from bs4 import BeautifulSoup
url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 提取数据
titles = soup.find_all('h2', class_='title')
for title in titles:
print(title.get_text())
在终端中,激活虚拟环境(如果有)并运行爬虫脚本:
source myenv/bin/activate
python my_spider.py
根据你的需求,可以选择不同的部署方式:
如果你需要更复杂的爬虫解决方案,可以考虑使用Scrapy框架:
pip install scrapy
scrapy startproject myproject
cd myproject
scrapy crawl myspider
如果你需要在爬虫中使用深度学习模型,可以考虑使用PyTorch:
pip install torch torchvision
# 保存模型
torch.save(model.state_dict(), 'model.pth')
# 加载模型
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load('model.pth'))
model.eval()
以上步骤可以帮助你在Ubuntu上部署Python爬虫。根据你的具体需求,可以选择适合的部署方式和工具。