2014-09-19 56 views
0

对于此代码,我将工作的python webcrawler从2.7转换为3.4。我做了一些修改,但运行时仍然出现错误:将python webcrawler从2.7转换为3.4

Traceback (most recent call last): 
    File "Z:\testCrawler.py", line 11, in <module> 
    for i in re.findall('''href=["'](.[^"']+)["']''', urllib.request.urlopen(myurl).read(), re.I): 
    File "C:\Python34\lib\re.py", line 206, in findall 
    return _compile(pattern, flags).findall(string) 
TypeError: can't use a string pattern on a bytes-like object 

这是代码本身,请告诉我,看看是什么语法错误。

#! C:\python34 

import re 
import urllib.request 

textfile = open('depth_1.txt','wt') 
print ("Enter the URL you wish to crawl..") 
print ('Usage - "http://phocks.org/stumble/creepy/" <-- With the double quotes') 
myurl = input("@> ") 
for i in re.findall('''href=["'](.[^"']+)["']''', urllib.request.urlopen(myurl).read(), re.I): 
     print (i) 
     for ee in re.findall('''href=["'](.[^"']+)["']''', urllib.request.urlopen(i).read(), re.I): 
       print (ee) 
       textfile.write(ee+'\n') 
textfile.close() 
+0

您需要解码从'read'到'str'的​​响应。 – roippi 2014-09-19 17:39:10

+2

虽然请 - 使用HTML解析器来解析HTML,而不是正则表达式。 – roippi 2014-09-19 17:39:42

回答

0

变化

urllib.request.urlopen(myurl).read() 

到例如

urllib.request.urlopen(myurl).read().decode('utf-8') 

这里会发生什么事是.read()返回bytes,而不是str就像是在Python 2.7,所以它必须使用一些解码编码。

相关问题