值错误:使用urllib对已关闭的文件执行I/O操作

2024-04-26 01:02:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我在从seekingalpha网站上获取数据时遇到了一个问题。我知道到目前为止,这个问题已经被问了好几次了,但提供的解决方案没有帮助

我有以下代码块:

class AppURLopener(urllib.request.FancyURLopener):
    version = "Mozilla/5.0"


def scrape_news(url, source):
    opener = AppURLopener()
    if(source=='SeekingAlpha'):
        print(url)
        with opener.open(url) as response:
            s = response.read()
            data = BeautifulSoup(s, "lxml")
            print(data)

scrape_news('https://seekingalpha.com/news/3364386-apple-confirms-hiring-waymo-senior-engineer','SeekingAlpha')

你知道这里出什么问题了吗?在

编辑: 全部回溯:

^{pr2}$

Tags: 代码urlsourcedata网站responseopener解决方案
1条回答
网友
1楼 · 发布于 2024-04-26 01:02:00

URL返回403。在终端中尝试此操作以确认:

curl -s -o /dev/null -w "%{http_code}" https://seekingalpha.com/news/3364386-apple-confirms-hiring-waymo-senior-engineer

或者,在Python repl中尝试以下操作:

^{pr2}$

FancyURLOpener正在接受关于失败响应代码的任何错误,这就是为什么您的代码继续执行response.read()而不是退出,即使它没有记录有效的响应。标准urllib.request.urlopen应该通过在403错误上引发异常来为您处理此问题,否则您可以自己处理。在

相关问题 更多 >