我使用beautifulsoup
在python中开发webcrawler,遇到了几个问题:
我不知道如何处理404s、503s之类的错误:目前,webcrawler只是中断程序执行
我不知道如何在页面中搜索特定的字符串,例如我是否希望它打印出包含字符串“Python”的页面
如果有人对我如何完成这两件事有任何意见,或者能把我推向正确的方向,我将不胜感激。你知道吗
目前我的代码是:
import urllib.request, time, unicodedata
from bs4 import BeautifulSoup
num = 0
def index():
index = open('index.html', 'w')
for x in range(len(titles)-1):
index.write("<a href="+'"'+tocrawl[x]+'"'+" "+"target=" "blank"" >"+titles[x+1]+"</a></br>\n")
index.close()
return 'Index Created'
def crawl(args):
page = urllib.request.urlopen(args).read()
soup = BeautifulSoup(page)
soup.prettify().encode('UTF-8')
titles.append(str(soup.title.string.encode('utf-8'),encoding='utf-8'))
for anchor in soup.findAll('a', href=True):
if str(anchor['href']).startswith(https) or str(anchor['href']).startswith(http):
if anchor['href'] not in tocrawl:
if anchor['href'].endswith(searchfor):
print(anchor['href'])
if not anchor['href'].endswith('.png') and not anchor['href'].endswith('.jpg'):
tocrawl.append(anchor['href'])
tocrawl, titles, descriptions, scripts, results = [], [], [], [], []
https = 'https://'
http = 'http://'
next = 3
crawl('http://google.com/')
while 1:
crawl(tocrawl[num])
num = num + 1
if num==next:
index()
next = next + 3
我正在使用python3.2,以防万一
处理错误代码:
当您试图打开一个URL并遇到错误时,您将得到一个HTTPError,其中方便地包含HTTP状态码和原因(例如,某个字符串)。如果要忽略错误,可以将函数包装在
try / except
块中并忽略错误:在页面中搜索字符串:} 方法返回结果就可以了。你知道吗
BeautifulSoup功能强大得难以置信;它的
find
方法(和find_all
方法)支持关键字参数text
,该参数使用正则表达式来查找页面中的文本。在您的例子中,因为您只需要确保文本存在,所以您可能只需要确保通过^{有关
text
参数can be found in the documentation的更多详细信息。你知道吗相关问题 更多 >
编程相关推荐