Python 名称错误:名称';htmltext';没有定义
运行此脚本时,我发现一个错误:Python 名称错误:名称';htmltext';没有定义,python,python-3.x,Python,Python 3.x,运行此脚本时,我发现一个错误: 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: t
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)
原scipt:
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 error[Errno-2]名称或服务未知
回溯(最近一次呼叫最后一次):
名称错误:未定义名称“htmltext”
如果
urllib.request.urlopen()
引发异常,htmltext
永远不会被分配值(因此在中打印该值除了将不起作用)
至于urlopen()
不起作用的原因,请确保您正在传递有效的URL。如果您将http://nytimes.com,http://nytimes.com
进入浏览器地址栏?此外,您的标题与描述不匹配(当然htmltext
在中没有定义,除了案例-您在那里是因为作业失败)。我不知道这是怎么回事,但现在正在工作,很抱歉,我理解为什么它工作,我从“url”值中删除了第二个地址,连接请求过程中可能会发生冲突,因为它被加倍了?非常感谢!直到现在我才明白“尝试”和“例外”的含义:D