首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NameError:未定义名称“htmltext”

NameError:未定义名称“htmltext”
EN

Stack Overflow用户
提问于 2014-10-26 18:51:03
回答 1查看 2K关注 0票数 0

运行此脚本时会获得一个错误:

代码语言:javascript
复制
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)

原始枕木:

代码语言:javascript
复制
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名称或服务未知 回溯(最近一次调用): NameError:未定义名称“htmltext”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-26 19:03:48

如果urllib.request.urlopen()引发异常,则htmltext永远不会得到一个值(因此在except中打印该值将无法工作)。

至于为什么urlopen()不能工作,请确保您正在传递一个有效的URL。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26576633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档