python-2.7 - 如何在使用python 2.7抓取URL时忽略HTTP错误

标签 python-2.7 http error-handling web-scraping web-crawler

我正在抓取多个URL,以在其源代码中找到特定的关键字。但是,在搜寻一半的网站时,由于404或503之类的HTTP错误,我的蜘蛛突然停了下来。

我的搜寻器:

import urllib2

keyword = ['viewport']

with open('listofURLs.csv') as f:
    for line in f:
        strdomain = line.strip()
        if strdomain:
            req = urllib2.Request(strdomain.strip())
            response = urllib2.urlopen(req)
            html_content = response.read()

            for searchstring in keyword:
                if searchstring.lower() in str(html_content).lower():
                    print (strdomain, keyword, 'found')

f.close()

我应该添加什么代码来忽略带有HTTP错误的错误URL,并让搜寻器继续爬网?

最佳答案

您可以使用try-except块,如here所示。这使您可以将逻辑应用于有效的URL,并将不同的逻辑应用于产生HTTP错误的URL。

将链接中的解决方案应用于代码即可。

import urllib2

keyword = ['viewport']

with open('listofURLs.csv') as f:
    for line in f:
        strdomain = line.strip()
        if strdomain:
            req = urllib2.Request(strdomain.strip())
            try:
                response = urllib2.urlopen(req)
                html_content = response.read()

                for searchstring in keyword:
                    if searchstring.lower() in str(html_content).lower():
                        print (strdomain, keyword, 'found')

            except urllib2.HTTPError, err:
                # Do something here maybe print err.code
f.close()

这是您提供的代码的正确解决方案。但是,eLRuLL提出了一个很重要的观点,您确实应该考虑使用scrapy满足您的Web爬网需求。

关于python-2.7 - 如何在使用python 2.7抓取URL时忽略HTTP错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355790/

相关文章:

python - 使用长度和字母顺序对列表进行排序

java - Android Studio 服务器连接失败

angular - 使用angular6的Http get方法

ios - NSURLConnection 有时会截断 NSMutableURLRequest 的主体

php - .htaccess 域根目录之外的错误页面

asp.net-mvc - 在MVC中显示捕获异常

python - Twisted 中的 OSError : [Errno 24] Too many open files when using reactor. run()

python - 退出和网络连接时出现Python错误代码

python-3.x - 使用tensorflow在CNN中出现尺寸错误

python - 错误 : Failed to load the native TensorFlow runtime in Python 2. 7