我正在使用python 2.7和urllib2命令来执行此操作。但是我面临错误,urllib2没有属性名称urlopen.Please help me.thanx,这是我的代码。
import urllib2
import re
pat = re.compile('target="_parent">(.*?)</a>')
url = 'http://timesofindia.indiatimes.com/home/headlines'
sock = urllib2.urlopen(url)
li = pat.findall(sock.read())
sock.close()
print li
f=open("headlines.txt", 'a+')
for i in range(len(li)):
f.write(li[i]+"\n")
f.close()
回溯
Error:Traceback (most recent call last):
File "C:/Users/Training/PycharmProjects/758702_Python_Program/ReadTOI/ReadTOI.py", line 1, in <module>
import urllib2
File "C:\Python27\lib\urllib2.py", line 111, in <module>
from urllib import (unwrap, unquote, splittype, splithost, quote,
File "C:\Users\Training\PycharmProjects\758702_Python_Program\urllib.py", line 4, in <module>
f=urllib.urlopen("http://www.python.org/")
AttributeError: 'module' object has no attribute 'urlopen'
答案 0 :(得分:2)
File "C:\Users\Training\PycharmProjects\758702_Python_Program\urllib.py", line 4, in <module>
您工作目录中的名称urllib.py
似乎有另一个文件。执行import urllib
python时导入的本地文件不包含urlopen()
。将本地文件重命名为其他内容或更改工作目录将解决此问题