Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式。Beautiful Soup 会帮你节省数大量工作时间。Beautiful Soup 3 目前已经停止开发,我们推荐在现在的项目中使用 Beautiful Soup 4。
安装
pip install beautifulsoup4
pip install lxml
pip install html5lib
解析
引用类库
import urllib.request as request
import bs4
获取网页
以全球主机交流论坛-美国VPS综合讨论板块首页为例:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
headers = {'User-Agent': user_agent}
req = request.Request('https://www.hostloc.com/forum-45-1.html', headers=headers)
page = request.urlopen(req).read().decode('utf-8')
soup = bs4.BeautifulSoup(page, "lxml")
查询和遍历
得到页面内容对象后,可以检索需要的内容,比如要得到帖子的标题和网址,通过查看网页源码,每个帖子主题位于 tr 标记内,首先要遍历得到所有的 tr 标记,然后继续解析得到最终内容:
trs = soup.find_all('tr')
for tr in trs:
th_new = tr.find('th', class_='new')
th_common = tr.find('th', class_='common')
if th_new:
a = th_new.find('a', href=re.compile(r'\bthread-'), class_='s xst')
elif th_common:
a = th_common.find('a', href=re.compile(r'\bthread-'), class_='s xst')
else:
continue
href = "https://www.hostloc.com/" + a['href'] //帖子地址
title = a.contents[0] //帖子地址
print(title,href)
以上是简单例子,更复杂的需求可以继续深入扩展功能。
脚本作为 ubuntu 服务
新建service文件:
vi /etc/systemd/system/monitor-hostloc-deal.service
[Unit]
Description=monitor-hostloc-deal daemon
Wants=NetworkManager-wait-online.service network-online.target
After=NetworkManager-wait-online.service network.target
#After=network.target
[Service]
#Type=oneshot
Type=simple
#User=root
WorkingDirectory=/var/www/My-SlowRead-Net
ExecStart=/usr/bin/python /var/www/My-SlowRead-Net/monitor-hostloc-deal.py
#ExecStart=/usr/bin/python -u /var/www/My-SlowRead-Net/monitor-hostloc-deal.py >> monitor-hostloc-deal.log
[Install]
WantedBy=multi-user.target
服务相关命令:
sudo systemctl daemon-reload
sudo systemctl enable monitor-hostloc-deal.service
sudo systemctl start monitor-hostloc-deal.service
sudo systemctl restart monitor-hostloc-deal.service
sudo systemctl status monitor-hostloc-deal.service
查看服务日志:
# 滚动显示某个 Unit 最新日志
journalctl -u monitor-hostloc-deal -f
控制台重定向
最简单常用的输出重定向方式是利用控制台命令。这种重定向由控制台完成,而与Python本身无关。
Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通过">"或">>"将输出重定向。其中,">"表示覆盖内容,">>"表示追加内容。类似地,"2>"可重定向标准错误。重定向到"nul"(Windows)或"/dev/null"(Linux)会抑制输出,既不屏显也不存盘。
E:\>echo print 'hello' > test.py
E:\>test.py > out.txt
E:\>type out.txt
hello
E:\>test.py >> out.txt
E:\>type out.txt
hello
hello
E:\>test.py > nul