【发布时间】:2020-10-24 03:27:57
【问题描述】:
我有以下代码,使用 BeautifulSoup 和 Python 对一些冠状病毒统计数据进行网络抓取(并随后计算出一个百分比):
url = "https://www.worldometers.info/coronavirus/"
req = requests.get(url)
bsObj = BeautifulSoup(req.text, "html.parser")
data = bsObj.find_all("div",class_ = "maincounter-number")
totalcases=data[0].text.strip()
recovered=data[2].text.strip()
print(totalcases+3)
percentagerecovered=recovered/totalcases*100
我遇到的问题是为已恢复的变量百分比生成所需的值。
我想使用整数,但上面的方法不起作用,所以我尝试了:
percentagecovered=int(recovered)/int(totalcases)*100 but it gave this error:
File "E:\webscraper\webscraper\webscraper.py", line 17, in <module>
percentagerecovered=int(recovered)/int(totalcases)*100
ValueError: invalid literal for int() with base 10: '6,175,537'
但是,当我删除铸件并尝试仅打印以查看它给出了不同错误的值时,我很难理解。
我改成:
totalcases=data[0].text.strip()
recovered=data[2].text.strip()
print(totalcases+3)
percentagerecovered=recovered/totalcases*100
错误
File "webscraper.py", line 16, in <module>
print(totalcases+3)
TypeError: can only concatenate str (not "int") to str
我只是想使用 split 方法获取这些字符串,然后假设它们是整数来处理它们。
目前,当我传递它们(不进行转换)时,它不会在页面上显示任何内容......但是当我将它们转换为 int 时,我会收到错误。我做错了什么?
我也试过了:
totalcases=int(totalcases)
recovered=int(recovered)
但这又产生了一个错误:
File "webscraper.py", line 17, in <module>
totalcases=int(totalcases)
ValueError: invalid literal for int() with base 10: '11,018,642'
我也试过这个:(去掉逗号)如下 cmets 中的建议:
totalcases=data[0].text.strip()
recovered=data[2].text.strip()
totalcases=totalcases.strip(",")
totalcases=int(totalcases)
recovered=recovered.strip(",")
recovered=int(recovered)
percentagerecovered=recovered/totalcases*100
错误:
totalcases=int(totalcases) ValueError: int() 以 10 为基数的无效文字:'11,018,684'
我注意到下面的函数(我还没有尝试过)之类的解决方案,但对于我正在尝试做的事情来说,它们似乎不必要地复杂。什么是最好、最简单/最优雅的解决方案。
这似乎是正确的,但仍然会产生错误:
int(totalcases.replace(',', ''))
int(recovered.replace(',', ''))
错误:
File "webscraper.py", line 25, in <module>
percentagerecovered=recovered/totalcases*100
TypeError: unsupported operand type(s) for /: 'str' and 'str'
【问题讨论】:
-
好的 - 感谢您的观察。但是我该如何将它作为一个整数来处理呢?
-
您可以去掉逗号,然后尝试转换为整数,
int("11,018,642".replace(",","")) -
我显然不能使用这个数字,因为它是动态生成的,并保存在变量 totalcases 和恢复中......所以我需要剥离,不知道确切的格式。
-
此外,如果我尝试 totalcases=int(totalcases.replace(",","")) 会导致错误:recovered=int(totalcases.replace(",","" )) AttributeError: 'int' 对象没有属性 'replace'
-
根据您的建议更新了上面的问题。
标签: python types beautifulsoup casting