繁体   English   中英

TypeError:描述符'split'需要'str' object,但收到'bytes'

[英]TypeError: descriptor 'split' requires a 'str' object but received a '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”object,但收到了一个“bytes”,您会得到任何帮助。 谢谢

利用

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

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

另一方面,请注意不再使用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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM