python 报错:a bytes-like object is required, not 'str'
核心代码:
def ipPools(numPage):
headers = randomHeads()
url = 'http://www.xicidaili.com/nn/'
saveFsvFile = open('ips.csv', 'wb')
writer = csv.writer(saveFsvFile)
for num in range(1, numPage + 1):
full_url = url + str(num)
re = requests.get(full_url, headers=headers)
soup = BeautifulSoup(re.text, 'lxml')
res = soup.find(id="ip_list").find_all('tr')
for item in res:
try:
temp = []
tds = item.find_all('td')
proxyIp = tds[1].text.encode("utf-8")
proxyPort = tds[2].text.encode("utf-8")
temp.append(proxyIp)
temp.append(proxyPort)
writer.writerow(temp)
print('保存为excel成功!')
except IndexError:
pass
注意点:
一定要将str转为bytes :
str.encode("utf-8")
python36 file方法改为open
open('ips.csv', 'wb')将wb改为w 我出错就在这。 如果有相同错误可以,作为参考吧!
推荐链接:
https://stackoverflow.com/questions/43582925/python-a-bytes-like-object-is-required-not-str-while-printing
https://blog.csdn.net/csu_vc/article/details/78372932
这两个可以看下。
本文作者:不随。
本文链接:https://www.cnblogs.com/tmblog/p/9357637.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步