2015-09-22 38 views
0

我正在编写一个小程序,通过提供一个URL来从网页中获取所有超链接,但它看起来像我所使用的网络使用代理,并且无法获取。 。 我的代码:如何通过代理使用Python访问网页

import sys 
import urllib 
import urlparse 

from bs4 import BeautifulSoup 
def process(url): 
    page = urllib.urlopen(url) 
    text = page.read() 
    page.close() 
    soup = BeautifulSoup(text) 
    with open('s.txt','w') as file: 
     for tag in soup.findAll('a', href=True): 
      tag['href'] = urlparse.urljoin(url, tag['href']) 
      print tag['href'] 
      file.write('\n') 
      file.write(tag['href']) 


def main(): 
    if len(sys.argv) == 1: 
     print 'No url !!' 
     sys.exit(1) 
    for url in sys.argv[1:]: 
     process(url) 
+0

根据您的问题,您的网络可能使用或不使用代理。你可以更具体一些,或只是通过管理员并询问? – frlan

+0

是的,它有一个代理,我试着在家里它工作正常,但当我把它给我的部门,以显示给我的老师,它的力量工作...这是错误 'IOError:[Errno套接字错误] [Errno -2]名称或服务未知' –

+0

这是我使用的代理连接“proxy4.nehu.ac.in:3128”我如何将它放在我的程序中的代码..?请帮助,我很困扰它。 –

回答

1

您可以改用请求模块。

import requests 

proxies = { 'http': 'http://host/ } 
# or if it requires authentication 'http://user:[email protected]/' instead 

r = requests.get(url, proxies=proxies) 
text = r.text 
+0

我应该把这样 'proxies = {'http':'http://proxya4.nehu.ac.in}' –

+0

您需要端口和结束报价。所以它会是'proxies = {'http':'http://proxya4.nehu.ac.in:3128'}' – blueteeth

+0

我可以再回到你身后,我会先尝试让你知道它是怎么回事? 。我真的想要这个工作..im喜欢在里面哭泣如此糟糕。 –

1

您使用HTTP访问不支持代理身份验证urllib库(它不支持未验证代理)。从the docs

Proxies which require authentication for use are not currently supported; this is considered an implementation limitation.

我建议你改用urllib2,并用它作为the answer to this post证明。

+0

我是新的python所以它很难实施,只是为了开始你可以以某种方式告诉我如何我应该把它放在我的程序中吗?? –

+0

我已经在python文档中看到,在urllib2中有一个可以处理代理的proxyHandler,我如何将它放入代理中,以便通过代理连接到internet.Please帮助 –