【问题标题】:Why does python think my variable is empty?为什么python认为我的变量是空的?
【发布时间】:2016-01-12 00:32:27
【问题描述】:

在我将 2 个 if 语句放入第三个代码块之前,我遇到了几乎相同的错误,即它无法连接 str 和 Nonetype。

但是,当我在第三个 if 语句中取消注释 print 语句时,它会打印出带有路径的 url 列表。

我也在其他网站上试过这个,不只是这个不起作用。

这是我的回溯

Traceback (most recent call last):
  File "linkcrawler.py", line 24, in <module>
    newurl = "http://" + b1 + b2
TypeError: cannot concatenate 'str' and 'NoneType' objects
Traceback (most recent call last):
  File "linkcrawler.py", line 24, in <module>
     newurl = "http://" + b1 + b2
TypeError: cannot concatenate 'str' and 'NoneType' objects

我每次运行它时只得到两个。

import urllib
from bs4 import BeautifulSoup
import traceback
import urlparse
import mechanize

url = "http://www.dailymail.co.uk/home/index.html"
br = mechanize.Browser()
urls = [url]
visited = [url]

while len(urls)>0:
    try:
        br.open(urls[0])
        urls.pop(0)
        for link in br.links():
            newurl = urlparse.urljoin(link.base_url,link.url)
            b1 = urlparse.urlparse(newurl).hostname
            b2 = urlparse.urlparse(newurl).path

            newurl = "http://"+b1+b2

            if newurl not in visited and urlparse.urlparse(url).hostname in newurl:
                urls.append(newurl)
                visited.append(newurl)
                #print newurl
    except:
        traceback.print_exc()
        urls.pop(0)
print visited

【问题讨论】:

  • b1b2(或两者)都是 None。你需要以某种方式解决它。
  • 它可能只是打印东西,直到 newurl = "http://"+b1+b2 失败,因为 b1 或 b2 之一是 None。
  • 显然没有主机名或路径。
  • 这不是您正在运行的代码。最好发布确切的功能。您真实代码中的错误发生在 newurl = ... 行中,但在您发布的内容中这是不可能的 - 它会在 len(b1)len(b2) 上引发异常。
  • 是的,你的权利我现在得到一个例外 b1

标签: python concatenation string-concatenation


【解决方案1】:

b1b2None。要解决此问题,请检查 b1b2 是否为空或 None 并重组您的代码:

b1 = urlparse.urlparse(newurl).hostname
b2 = urlparse.urlparse(newurl).path

if b1 and b2:
    newurl = "http://"+b1+b2
    if newurl not in visited and urlparse.urlparse(url).hostname in newurl:
        urls.append(newurl)
        visited.append(newurl)
        #print newurl
else:
    urls.pop(0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    相关资源
    最近更新 更多