【问题标题】:NameError: name 'htmltext' is not definedNameError:名称'htmltext'未定义
【发布时间】:2014-12-21 23:40:36
【问题描述】:

运行此脚本时出现错误:

import urllib.request
import urllib.parse
from bs4 import BeautifulSoup

url = "http://nytimes.com,http://nytimes.com"

urls = [url] #stack of urls to scrape
visited = [url] #historic record of urls

while len(urls) >0:
try:
    htmltext = urllib.request.urlopen(urls[0]).read()
except:
    print(htmltext)

原文:

import urllib.request
import urllib.parse
from bs4 import BeautifulSoup

url = "http://nytimes.com,http://nytimes.com"

urls = [url] #stack of urls to scrape
visited = [url] #historic record of urls

while len(urls) >0:
try:
    htmltext = urllib.request.urlopen(urls[0]).read()
except:
    print(urls[0])
soup = BeautifulSoup(htmltext)

urls.pop(0)

print (soup.findAll('a',href=True))

错误:

socket.gaierror: [Errno -2] 名称或服务未知

urllib.error.URLError: urlopen 错误 [Errno -2] 名称或服务未知

Traceback(最近一次调用最后一次):

NameError: name 'htmltext' 未定义

【问题讨论】:

  • 如果您将http://nytimes.com,http://nytimes.com 放入浏览器地址栏中会发生什么?此外,您的标题与描述不符(但 当然 htmltext 未在 except 案例中定义 - 您在那里是因为分配 失败) .
  • 我不知道这怎么可能,但现在正在工作,对不起
  • 我明白它为什么起作用了,我从“url”值中删除了第二个地址,连接请求期间可能发生冲突,因为它被加倍了?

标签: python python-3.x


【解决方案1】:

如果urllib.request.urlopen() 引发异常,htmltext 永远不会被分配一个值(因此在except 中打印该值将不起作用)。

至于为什么urlopen() 不起作用,请确保您传递的 URL 有效。

【讨论】:

  • 非常感谢!直到现在我才明白“尝试”和“除外”的含义:D
猜你喜欢
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2021-04-15
  • 2019-01-26
  • 2021-10-05
  • 2017-08-16
  • 2019-08-18
相关资源
最近更新 更多