关于 urllib 的 AttributeError:‘module’对象没有属性‘urlopen’
import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display
#what i plan to do with it once i get the first part working
#results = re.findall('[<td style="font-weight:bold;" nowrap>$][0-9][0-9][0-9][.][0-9][0-9][</td></tr></tfoot></table>]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()
这是我目前写的代码。我查看了其他论坛上提供的解决方案,比如这个脚本的名字是parse_Money.py。我尝试过用urllib.request.urlopen来运行它,也试过在Python 2.5、2.6和2.7上运行。如果有人有任何建议,我会非常感激,谢谢大家!!
---编辑---
我还尝试了这段代码,并且它成功运行了,所以我在想可能是某种语法错误。如果有眼尖的人能指出来,我会非常感激。
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3
#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')
while b == 3:
#get file name
file1 = raw_input('Enter a file name for the downloaded code:')
filepath = file1 + '.txt'
if os.path.isfile(filepath):
print 'File already exists'
b = 3
else:
print 'Filename accepted'
b = 4
file_path = filepath
#open file
FileWrite = open(file_path, 'a')
#acces URL
filehandle = urllib.urlopen(URL)
#display souce code
for lines in filehandle.readlines():
FileWrite.write(lines)
print lines
print 'The above has been saved in both a text and html file'
#close files
filehandle.close()
FileWrite.close()
3 个回答
0
我看到你在使用Python2,或者至少打算使用Python2。
urlopen
这个辅助函数在Python2的urllib和urllib2库中都有。
你需要做的是,确保这个脚本在你正确版本的Python上运行。
C:\Python26\python.exe yourscript.py
0
urlopen这个函数其实是在urllib2这个模块里。你可以试着先导入urllib2,然后使用urllib2.urlopen这个函数。
1
看起来,urlopen
这个方法是在urllib.request
模块里,而不是你期待的urllib
模块里。
一个简单的经验法则是,如果你遇到AttributeError
错误,那说明这个字段或操作在你使用的模块里是不存在的。
补充说明 - 感谢AndiDog的提醒,这个解决方案适用于Python 3.x,不适用于Python 2.x!