写入Excel问题
本帖最后由 Vastsea 于 2020-5-13 13:25 编辑如果采用这个代码,Excel的数值只有从最后一个IP获取的数值。
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ip = ['10.0.3.12','10.0.55.20','10.0.3.18','10.0.70.18','10.0.3.15','10.0.70.24']
for i in ip:
url = "http://" + i + "/web/guest/cn/websys/status/getUnificationCounter.cgi"
req = requests.get(url)
html = req.text
bs = BeautifulSoup(html,"html.parser")
trs = bs.select('tr.staticProp').get_text()
count = trs
ws.title
ws['A1'] = "IP地址"
ws['B1'] = "总数"
for n in count:
ws.append()
wb.save(""c:\\New folder\\11.xlsx"")
改成如下代码,提示错误。
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ip = ['10.0.3.12','10.0.55.20','10.0.3.18','10.0.70.18','10.0.3.15','10.0.70.24']
for i in ip:
url = "http://" + i + "/web/guest/cn/websys/status/getUnificationCounter.cgi"
req = requests.get(url)
html = req.text
bs = BeautifulSoup(html,"html.parser")
trs = bs.select('tr.staticProp').get_text()
n = n+1
n = 1
count = trs
ws.title
ws['A1'] = "IP地址"
ws['B1'] = "总数"
for n in ip:
ws.append(ws['A+n'],ws['B+n'])
wb.save("c:\\New folder\\11.xlsx")
报错如下:
TypeError Traceback (most recent call last)
<ipython-input-5-122806803084> in <module>
13 trs = bs.select('tr.staticProp').get_text()
14 print(i,trs)
---> 15 n == n+1
16 n == 1
17 count = trs
TypeError: can only concatenate str (not "int") to str
TypeError:不同类型间的无效操作。
python认为第15行的“n”的值是文本。
宋恺 发表于 2020-5-13 16:53
TypeError:不同类型间的无效操作。
python认为第15行的“n”的值是文本。
该如何更正? 程序的目的是什么,解决什么问题?
光看代码有很多处逻辑不通的,不知道你的意图不好说。 本帖最后由 有谁懂 于 2020-5-13 20:00 编辑
Vastsea 发表于 2020-5-13 19:34
该如何更正?
把 n=1 和n = n+1 换一下试试。
你在计算前 要先给n赋值吧。
而且你缩进好像也有问题,不太明白n = n+1有什么意义。
建议加上注释来提问! suchocolate 发表于 2020-5-13 19:44
程序的目的是什么,解决什么问题?
光看代码有很多处逻辑不通的,不知道你的意图不好说。
就是想将bs.select('tr.staticProp').get_text()获得的结果写如到excel里面,得到下面的结果。(真实结果数值是不同的,只是举例用了同样的数值。)
IP地址 总数
10.0.3.12 40355
10.0.55.20 40355
10.0.3.18 40355
10.0.70.18 40355
10.0.3.15 40355
10.0.70.24 40355
Vastsea 发表于 2020-5-13 20:36
就是想将bs.select('tr.staticProp').get_text()获得的结果写如到excel里面,得到下面的结果。(真实 ...
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws['A1'] = "IP地址"
ws['B1'] = "总数"
n = 2
ip = ['10.0.3.12','10.0.55.20','10.0.3.18','10.0.70.18','10.0.3.15','10.0.70.24']
for i in ip:
url = "http://" + i + "/web/guest/cn/websys/status/getUnificationCounter.cgi"
req = requests.get(url)
html = req.text
bs = BeautifulSoup(html,"html.parser")
trs = bs.select('tr.staticProp').get_text()
r = str(n)
n = n + 1
ws['a' + r] = i
ws['b' + r] = trs
wb.save("c:\\New folder\\11.xlsx")
页:
[1]