【问题标题】:NameError in Python 3.4.3Python 3.4.3 中的名称错误
【发布时间】:2016-03-12 16:01:42
【问题描述】:

当我尝试使用以下配置时:

  • 带有 python3.4.3 的虚拟环境
  • 在在线 IDE 上运行

当我尝试这个时:

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup
try:
    html = urlopen("http://www.pythonscraping.com/pages/pages1.html")

if html is None:
        print("url not found")
else:
    except HTTPError as e:
        print("test")
    else:
        bsObj = BeautifulSoup(html.read())
        print(bsObj)

我收到以下错误:

~/workspace/scrapingEnv $ python test2.py
  File "test2.py", line 7
    if html is None:
     ^
SyntaxError: invalid syntax

我做错了什么?

【问题讨论】:

  • 你有 try/exceptif/else 嵌套奇怪......
  • 缩进在 Python 中很重要,如果这是对文件格式的准确表示,则它不是有效的 Python。

标签: python beautifulsoup syntax-error


【解决方案1】:

感谢您的提示,我找到了解决问题的方法:

from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup

try:
    html = urlopen("http://www.pythonscrapng.com/pages/pages1.html")
    bsObj = BeautifulSoup(html.read())
    print(bsObj)

except HTTPError as e:
    print("test")
except URLError as j:
    print ("No URL")
else:
    bsObj = BeautifulSoup(html.read())
    print(bsObj)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多