【问题标题】:Beautiful Soup error: NameError: name 'htmltext' is not definedBeautiful Soup 错误:NameError: name 'htmltext' is not defined
【发布时间】:2014-05-09 17:21:28
【问题描述】:

我收到此错误:

NameError: name 'htmltext' is not defined

来源于以下代码:

from bs4 import BeautifulSoup
import urllib
import urllib.parse

url = "http://nytimes.com"

urls = [url]
visited = [url]

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

        soup = BeautifulSoup(htmltext)    
        urls.pop(0)

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

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    在 Python 3.x 中,您必须导入 urllib.request 而不是 urllib。然后,换行:

    htmltext = urllib.urlopen(urls[0]).read()
    

    到:

    htmltext = urllib.request.urlopen(urls[0]).read()
    

    最后,将true 更改为True。

    【讨论】:

    • 如果try 块失败并且except 块被执行,使用htmltext 参数调用BeautifulSoup 将导致问题。也许将其余代码添加到try 块?
    • 你是对的,最好包含更多的错误处理,例如,url 无效。照原样,我建议的更改将适用于这种特殊情况,但我同意它可以进一步改进。
    • 谢谢大家。这真的很有帮助,我假设 Beautiful soup 安装不正确,但我现在看到 python 的语法可能很棘手。再次感谢。
    猜你喜欢
    • 2020-11-07
    • 2022-11-27
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多