【问题标题】:ValueError: read of closed fileValueError:读取已关闭的文件
【发布时间】:2019-04-24 18:37:11
【问题描述】:

我正在尝试使用 BeautifulSoup 解析一些页面,但是对于某些链接,开启程序不起作用。这是开瓶器的代码:

class URLopener(urllib.request.FancyURLopener):
    version = "Mozilla/5.0"
    def http_error_default(self, url, fp, errcode, errmsg, headers):
        if errcode == 403:
            raise ValueError("403")
        return super(URLopener, self).http_error_default(
            url, fp, errcode, errmsg, headers
        )

现在当它试图用这段代码打开和解析一些页面时:

opener = URLopener()
page = opener.open(url)
soup = BeautifulSoup(page.read(), features='lxml')
links = soup.findAll("a", href=True)

它工作正常。但是当它到达这样的链接时:

http://scholar.google.com/citations%3Fview_op%3Dsearch_authors%26hl%3Den%26mauthors%3Dlabel:deep_learning

它突然停止并显示错误:

如何过滤搜索的页面以避免此问题?我不一定想要搜索结果中的所有页面。

【问题讨论】:

  • 你可以试试urllib.parse.unquote(url)

标签: python beautifulsoup python-requests web-crawler


【解决方案1】:

您的某些网址采用带引号的形式。这可以使用 Python 的 unquote() 函数轻松删除,如下所示:

import urllib.parse


opener = URLopener()
page = opener.open(urllib.parse.unquote(url))
soup = BeautifulSoup(page.read(), features="lxml")
links = soup.find_all("a", href=True)

这会将您提供的示例 URL 转换为以下格式:

http://scholar.google.com/citations?view_op=search_authors&hl=en&mauthors=label:deep_learning

【讨论】:

    猜你喜欢
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2017-03-20
    • 2016-07-21
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多