0

我一直在使用 python 开发网络爬虫,但beautifulsoup遇到了几个问题:

  1. 我不知道如何处理 404s、503s 或其他类似错误:目前,网络爬虫只是中断了程序执行

  2. 我不知道如何在页面中搜索特定字符串,例如如果我希望它打印出包含字符串“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

我正在使用 Python 3.2,以防万一

4

1 回答 1

1

处理错误代码:
当您尝试打开一个 URL 并遇到错误时,您将收到一个HTTPError,其中包含 HTTP 状态代码和原因(例如一些字符串)。如果要忽略错误,可以将函数包装在一个try / except块中并忽略错误:

try:
    page = urllib.request.urlopen(args).read()
    # ...
except urllib.error.HTTPError as e:
    # we don't care about no stinking errors
    # ... but if we did, e.code would have the http status code...
    # ... and e.reason would have an explanation of the error (hopefully)
    pass

在页面中搜索字符串:
美丽的汤非常强大;它的find方法(及其find_all方法)支持关键字参数text,该参数使用正则表达式来查找页面中的文本。在您的情况下,由于您只需要确保文本存在,因此您可能只需确保通过该find方法返回结果即可。

if soup.find(text=re.compile('my search string')):
    # do something

可以在文档中找到text有关该参数的更多详细信息。

于 2013-06-09T03:09:19.363 回答