检查网站中特定标签的Python脚本
我正在尝试写一个网站监控的脚本(最后会变成定时任务),这个脚本的工作是打开一个指定的网址,检查一下某个标签是否存在。如果这个标签不存在,或者里面没有我期待的数据,那么就把这些信息写入一个日志文件,或者发送一封电子邮件。
这个标签可能是像
有没有人有什么好主意呢?
3 个回答
1
下面这段(未经测试的)代码使用了urllib2来获取网页内容,并用re来进行搜索。
import urllib2,StringIO
pageString = urllib2.urlopen('**insert url here**').read()
m = re.search(r'**insert regex for the tag you want to find here**',pageString)
if m == None:
#take action for NOT found here
else:
#take action for found here
下面这段(未经测试的)代码使用了pycurl和StringIO来获取网页内容,并用re来进行搜索。
import pycurl,re,StringIO
b = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(pycurl.URL, '**insert url here**')
c.setopt(pycurl.WRITEFUNCTION, b.write)
c.perform()
c.close()
m = re.search(r'**insert regex for the tag you want to find here**',b.getvalue())
if m == None:
#take action for NOT found here
else:
#take action for found here
2
这是一个示例代码(未经测试),用于记录日志并发送邮件:
#!/usr/bin/env python
import logging
import urllib2
import smtplib
#Log config
logging.basicConfig(filename='/tmp/yourscript.log',level=logging.INFO,)
#Open requested url
url = "http://yoursite.com/tags/yourTag"
data = urllib2.urlopen(url)
if check_content(data):
#Report to log
logging.info('Content found')
else:
#Send mail
send_mail('Content not found')
def check_content(data):
#Your BeautifulSoup logic here
return content_found
def send_mail(message_body):
server = 'localhost'
recipients = ['you@yourdomain.com']
sender = 'script@yourdomain.com'
message = 'From: %s \n Subject: script result \n\n %s' % (sender, message_body)
session = smtplib.SMTP(server)
session.sendmail(sender,recipients,message);
我会用beautifulSoup来编写check_content()
这个函数。
5
我觉得你最好的选择是看看BeautifulSoup这个工具。用法大概是这样的:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://yoursite.com")
soup = BeautifulSoup(page)
# See the docs on how to search through the soup. I'm not sure what
# you're looking for so my example stops here :)
之后,把它发邮件或者记录下来都是很常见的做法。