String python:TypeError:应为字符串或缓冲区:can';不能用提示符再现错误

String python:TypeError:应为字符串或缓冲区:can';不能用提示符再现错误,string,python-2.7,String,Python 2.7,我正在尝试调试此函数: def check_domains(url): global num_websites,domain_queue,domains,doc_queue,stanford_tagger the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url) if the_domain is not None: if the_domain.groups(0)[1] not in domains.k

我正在尝试调试此函数:

def check_domains(url):
 global num_websites,domain_queue,domains,doc_queue,stanford_tagger
 the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url)
 if the_domain is not None:
  if the_domain.groups(0)[1] not in domains.keys():
   domains[the_domain.groups(0)[1]] = website(doc_queue,the_domain.groups(0)[1])
   domains[the_domain.groups(0)[1]].add_initial_url(url)
   domain_queue.append(domains[the_domain.groups(0)[1]])
   num_websites = num_websites + 1
  else:
   domains[the_domain.groups(0)[1]].add_url(url)
错误:

  File "web_crawler.py", line 178, in getdoc
    check_domains(check)
  File "web_crawler.py", line 133, in check_domains
    the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url)
  File "/usr/local/lib/python2.7/re.py", line 137, in match
    return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
我试着做一个好孩子,在互动模式下测试:

>>> def check_domains(url):
...  the_domain = re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$',url) #right here
...  if the_domain is not None:
...   print the_domain.groups(0)[1]
...  else:
...   print "NOOOO!!!!!"
... 
>>> 
>>> check_domains("http://www.hulu.com/watch/6704")
hulu.com
>>> check_domains("https://docs.python.org/2/library/datetime.html")
python.org

所以这就是我想要它做的,我没有改变那条线。但是为什么呢?

url的值仍然可以是
None
,这就是产生此错误的原因:

>>> re.match(r'^(:?https?:\/\/[^.]*\.)?([^/#?&]+).*$', None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 137, in match
    return _compile(pattern, flags).match(string)
TypeError: expected string or buffer
>>re.match(r'^(:?https?:\/\/[^.]*\)?([^/#?&]+).*$,无)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py”,第137行,匹配
返回编译(模式、标志)。匹配(字符串)
TypeError:应为字符串或缓冲区

因此,您应该检查为
url
传递的对象是否确实是字符串。它甚至可能是一个数字或其他东西,但它不是匹配函数所期望的字符串。

谢谢,我没有缩小它的范围,但它以某种方式得到了修复