Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 名称错误:名称';htmltext';没有定义_Python_Python 3.x - Fatal编程技术网

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