AttributeError:'模块'对象没有属性' urlopen'在urllib3中

时间:2016-05-15 16:21:33

标签: python urllib3

我已经检查了其他帖子,但解决方案似乎没有用。我一直得到AttributeError:'模块'对象没有属性' urlopen'错误。任何想法,为什么这不会工作非常感激。

from lxml import html
import requests
import urllib3

page = requests.get('http://www.sfbos.org/index.aspx?page=18701')
tree = html.fromstring(page.content)

#This will create a list of buyers:
proposal_doc_date = tree.xpath('//ul[@title="Date List"]/li/a/text()')
pdf_url = tree.xpath('//ul[@title="Date List"]/li/a/@href')

print 'Proposal Date ', proposal_doc_date
print 'Proposal PDF ', pdf_url

def download_pdf(url_list):
    for i in url_list:
        response = urllib3.urlopen(i)
        file = open(proposal_doc_date[i], 'wb')
        file.write(response.read())
        file.close()
        print("Completed")

download_pdf(pdf_url)

2 个答案:

答案 0 :(得分:0)

您正在导入具有相同目的的requestsurllib3(请求建立在urllib3之上)。以下是使用请求执行此操作的方法:

import requests

# ...

http = requests.Session()

def download_pdf(url_list):
    for i in url_list:
        response = http.get(i)
        file = open(proposal_doc_date[i], 'wb')
        file.write(response.content)
        file.close()
        print("Completed")

urllib3中的类似场景:

import urllib3

# ...

http = urllib3.PoolManager()

def download_pdf(url_list):
    for i in url_list:
        response = http.request('GET', i)
        file = open(proposal_doc_date[i], 'wb')
        file.write(response.read())
        file.close()
        print("Completed")

您可以使用流式传输请求以及在流式传输时将响应写入文件来执行各种其他操作。查看相应项目的文档了解更多信息。

答案 1 :(得分:-1)

urlopen似乎是urllib3.connectionpool.HTTPConnectionPool类的方法

https://urllib3.readthedocs.io/en/latest/pools.html#urllib3.connectionpool.HTTPConnectionPool.urlopen