微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类型错误:描述符 'split' 需要一个 'str' 对象,但收到了一个 'bytes'

如何解决类型错误:描述符 'split' 需要一个 'str' 对象,但收到了一个 'bytes'

我正在尝试使用 Github 上提供的 Python 脚本从 ESPN Cricinfo 抓取数据。代码如下。

import urllib.request as ur
import csv
import sys
import time
import os
import unicodedata
from urllib.parse import urlparse
from bs4 import BeautifulSoup

BASE_URL = 'http://www.espncricinfo.com'
for i in range(0,6019):
url = 'http://search.espncricinfo.com/ci/content/match/search.html?search=first%20class;all=1;page='
    soupy = BeautifulSoup(ur.urlopen(url + str(i)).read())

    time.sleep(1)
    for new_host in soupy.findAll('a',{'class' : 'srchPlyrNmTxt'}):
        try:
            new_host = new_host['href']
        except:
            continue
        odiurl = BASE_URL + urlparse(new_host).geturl()
        new_host = unicodedata.normalize('NFKD',new_host).encode('ascii','ignore')
        print (new_host)
        print (str.split(new_host,"/"))[4]
        html = urllib2.urlopen(odiurl).read()
        if html:
            with open('espncricinfo-fc/{0!s}'.format(str.split(new_host,"/")[4]),"wb") as f:
                f.write(html)

错误在这一行。

print (str.split(new_host,"/"))[4]

TypeError: 描述符 'split' 需要一个 'str' 对象,但收到了一个 'bytes' 来自您的任何帮助都会受到赞赏。谢谢

解决方法

使用

str.split(new_host.decode("utf-8"),"/")[4]

.decode("utf-8") 显然是最重要的部分。这会将您的 byte 对象转换为字符串。

另一方面,请注意 urllib2(顺便说一下,您正在使用但未导入)不再使用(请参阅 this)。相反,您可以使用 from urllib.request import urlopen

编辑:这是完整的代码,不会给您您在问题中描述的错误。我要强调的是,因为如果没有之前创建的文件,with open(...) 语句会给您一个 FileNotFoundError

import urllib.request as ur
import csv
import sys
import time
import os
import unicodedata
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from urllib.request import urlopen

BASE_URL = 'http://www.espncricinfo.com'
for i in range(0,6019):
    url = 'http://search.espncricinfo.com/ci/content/match/search.html?search=first%20class;all=1;page='
    soupy = BeautifulSoup(ur.urlopen(url + str(i)).read())

    time.sleep(1)
    for new_host in soupy.findAll('a',{'class' : 'srchPlyrNmTxt'}):
        try:
            new_host = new_host['href']
        except:
            continue
        odiurl = BASE_URL + urlparse(new_host).geturl()
        new_host = unicodedata.normalize('NFKD',new_host).encode('ascii','ignore')
        print(new_host)
        print(str.split(new_host.decode("utf-8"),"/")[4])
        html = urlopen(odiurl).read()
        if html:
            with open('espncricinfo-fc/{0!s}'.format(str.split(new_host.decode("utf-8"),"/")[4]),"wb") as f:
                f.write(html)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。