AttributeError: 'module' object has no attribute 'urlopen' in urllib3

AttributeError: 'module' object has no attribute 'urlopen' in urllib3

我查看了其他帖子,但解决方案似乎没有用。我不断收到 AttributeError: 'module' object has no attribute '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)

urlopen 好像是urllib3.connectionpool.HTTPConnectionPoolclass

的方法

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

您正在导入两个 requests and urllib3,它们的目的相同(请求建立在 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")

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