【问题标题】:Overriding HTTP errors with urllib2使用 urllib2 覆盖 HTTP 错误
【发布时间】:2015-03-02 00:23:03
【问题描述】:

我有这个代码,但它不工作。我想使用 urllib2 来遍历 url 列表。在打开每个 url 时,BeautifulSoup 会找到一个类并提取该文本。如果列表中有无效的 url,程序就会停止。如果有任何错误,我只想将“错误”作为文本,并让程序继续到下一个 url。有什么想法吗?

    for url in url_list:
         page=urllib2.urlopen(url)
         soup = BeautifulSoup(page.read())

         text = soup.find_all(class_='ProfileHeaderCard-locationText u-dir')
         if text is not None:
            for t in text:
                text2 = t.get_text().encode('utf-8')
         else:
            text2 = 'error'

【问题讨论】:

    标签: python http beautifulsoup urllib2


    【解决方案1】:

    try/except 是你的朋友!将您的代码更改为类似...:

    for url in url_list:
        try:
            page = urllib2.urlopen(url)
        except urllib2.URLError:
            text2 = 'error'
        else:
            soup = BeautifulSoup(page.read())
            text = soup.find_all(class_='ProfileHeaderCard-locationText u-dir')
            if text:
               for t in text:
                   text2 = t.get_text().encode('utf-8')
            else:
               text2 = 'error'
    

    【讨论】:

    • [] is not None 永远为真
    • @PadraicCunningham 是的,因为这就是find_all 在没有点击时返回的内容,所以我将编辑我的 A 以通过 OP 解决这个进一步的问题(我最初只是来自 Q 的 c&p :-) .
    • @AlexMartelli 非常感谢!这解决了它。我是否正确理解它首先检查URLError,最后检查任何其他错误?
    • @textnet,否:它检查 only 是否存在 URLError,else: 部分仅在没有错误时执行——任何其他异常在这里都是意外的,因此,作为最佳实践,它允许向上传播调用堆栈。
    【解决方案2】:

    urllib2.urlopen 在错误时引发 URLError,您可以在 docs 中找到该错误

    使用 try-except 块:

    try:
        page = urllib2.urlopen(url)
    except urllib2.URLError as e:
        print e
    

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 2012-02-09
      • 1970-01-01
      • 2015-12-03
      • 2018-04-29
      • 1970-01-01
      相关资源
      最近更新 更多