我正在尝试将一些代码升级到Python 3,以便它使用Requests库。原始代码使用urllib2,后者适用于Python的早期版本(我认为仅适用于Python 2)。许多SO响应带来了有关httplib2或更旧协议的太多细节。
我正在尝试使以下程序在Python 3中运行:
import bs4, urllib2, pandas, datetime, random, math, numpy
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
# SOCIAL SECURITY ACTUARIAL LIFE TABLE
url = "https://www.ssa.gov/oact/STATS/table4c6.html"
page = urllib2.urlopen(url)
soup = bs4.BeautifulSoup(page.read(), 'html.parser')
table = soup.find("table")#.get_text()
Life_List, j = ([], 0)
for tr in table.findAll("tr")[4:]:
row = []
td = tr.findAll("td")
for columns in range(0 , 7):
string = td[columns].text.replace(',', '')
value = pandas.to_numeric(string)
row.append(value)
Life_List.append(row)
names = ["Age", "P(M)", "n(M)", "E(M)", "P(F)", "n(F)", "E(F)"]
Life_Table = pandas.DataFrame(Life_List, columns=names)
# For computational convenience, no one lives to more than 120 years
Life_Table.set_value(119, "P(M)", 1.0)
Life_Table.set_value(119, "P(F)", 1.0)
plt.figure(1)
for i in (1, 3, 4, 6):
plt.subplot(211 + i % 3)
if i == 1 or i == 3:
p = plt.plot(Life_Table[names[0]], Life_Table[names[i]], 'b-', label="Male")
else:
p = plt.plot(Life_Table[names[0]], Life_Table[names[i]], 'r-', label="Female")
if i == 1 or i == 4:
plt.ylabel('Probability of Death')
legend()
else:
plt.ylabel('Life Expectancy')
legend()
plt.savefig(".\DATA_602_Project_1.png")
# plt.show()
plt.clf()
所需的代码更新不清楚,因为urllib,urllib2,urllib3和请求似乎都做了一些但不是全部相同的事情。它们不是彼此的直接替代品,并且不可互换。
我需要知道如何获取使用urllib2,urllib或urllib3代码的任何代码,并将其与Python 3的请求库一起使用。
我不确定在哪里进行更改(导入urllib2->导入请求,然后(urllib2.urlopen(url)->请求...(url)??)),但是还有什么呢? / p>
有人可以仅使用Python 3的请求库解释执行此操作所需的更改。我不再关心Python 2,仅关心如何将旧代码更新为Python3。我需要解释以下代码中所需的代码更改,以便它在Python 3中起作用。
更改以下几行将返回一个页面,但这是一个bytes
对象,并在Python 3中引发AttributeError。
import bs4, urllib2
# SOCIAL SECURITY ACTUARIAL LIFE TABLE
url = "https://www.ssa.gov/oact/STATS/table4c6.html"
page = urllib2.urlopen(url)
soup = bs4.BeautifulSoup(page.read(), 'html.parser')
table = soup.find("table")#.get_text()
到
import bs4, requests
# SOCIAL SECURITY ACTUARIAL LIFE TABLE
url = "https://www.ssa.gov/oact/STATS/table4c6.html"
page = requests.get(url)
soup = bs4.BeautifulSoup(page.read(), 'html.parser')
table = soup.find("table")#.get_text()
给出以下输出:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-30-70d694afd0ab> in <module>
----> 1 soup = bs4.BeautifulSoup(r_content.read(), 'html.parser')
2 table = soup.find("table")#.get_text()
AttributeError: 'bytes' object has no attribute 'read'
#
我希望看到所有必需的代码更改,以便上面的整个程序都可以在Python 3中运行,以及为什么需要进行特定更改,而不仅仅是简短说明的代码段。自从我开始使用Python Web工具以来,这个urllib2到Requests库的转换使我感到困惑。请不要引入其他功能或库,例如http2lib,因为这只会使问题感到困惑。谢谢。