2016-03-05 92 views
-1

我正在尝试获取网页的内容。由于某种原因,每当我尝试urlopen它说有没有这样的资源。我也不能使用urllib2。用Python阅读网页的内容

我只想得到这样一个网页的内容http://www.example.com

import urllib 
import re 

textfile = open('depth_1.txt','w') 
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.urlopen(myurl).read(), re.I): 
    print(i) 
    for ee in re.findall('''href=["'](.[^"']+)["']''', urllib.urlopen(i).read(), re.I): 
      print(ee) 
      textfile.write(ee+'\n') 
textfile.close() 

以下是错误:

Traceback (most recent call last): 
    File "/Users/austinhitt/Desktop/clases_example.py", line 8, in <module> 
    for i in re.findall('''href=["'](.[^"']+)["']''', 
urllib.urlopen(myurl).read(), re.I): 
AttributeError: module 'urllib' has no attribute 'urlopen' 
+0

您正在使用Python 3,但res您从中学习Python已经过时了,并且使用了Python 2.'urllib2'在Python 3中没有更多的功能,它的功能主要存在于'urllib'及其子模块 –

+2

对于学习资源我推荐[自动化无聊的东西Python](https://automatetheboringstuff.com/),其中包括使用Python 3的网页抓取章节。 –

+0

@AnttiHaapala我同意你的意见。因此我需要知道如何在python 3中打开一个url。我的IDLE shell说url urlopen不起作用。 – HittmanA

回答

0

仅适用于内容的使用要求,如果你想角落找寻玩与您需要使用scrapy的内容,例如:

import requests 
r = requests.get('http://scrapy.org') 
r.content 
r.headers 
r.status_code 
+0

我不确定为什么你在示例代码中声明scrapy是必需的。 – tagoma

+0

不,我说如果他只想要内容他可以使用请求,但如果他需要别的东西,他可以使用scrapy,我的例子是使用请求。 –