TypeError:只能连接str

2024-05-02 18:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作加菲猫视频下载器。我遇到了这个错误,不知道如何修复它

Error:
Traceback (most recent call last):
  File "/Users/Jake/Desktop/garfield copy 2.py", line 10, in <module>
    url = 'http://pt.jikos.cz/garfield/' + year + '/' + month
TypeError: can only concatenate str (not "int") to str

代码:

# Downloads Garfield Comic

import requests, os, bs4, threading
print('\t\t---------Garfield Comic Download---------')
t = 1
print('Enter the Year:')
year = input()
month = 1
while t < 12:
        url = 'http://pt.jikos.cz/garfield/' + year + '/' + month
        location = 'Garfield(' + month + '-' + year + ')'
        os.makedirs(location, exist_ok=True)

        def downloadGarfield(comicElem, startNum, endNum):
                # Download the images
                for i in range(startNum, endNum):
                        comicUrl = comicElem[i].get('src')
                        # Download the image.
                        print('Downloading the image %s...' % (comicUrl))
                        res = requests.get(comicUrl)
                        res.raise_for_status()

                        # Save the image to ./Garfield(month-year).
                        imageFile = open(os.path.join(location, os.path.basename(comicUrl)), 'wb')
                        for chunk in res.iter_content(100000):
                                imageFile.write(chunk)
                        imageFile.close()

        # Download the page.
        print('Downloading page %s...' % url)
        res = requests.get(url)
        res.raise_for_status()

        soup = bs4.BeautifulSoup(res.text,'lxml')

        # Find the URL of the comic image.
        comicElem = soup.select('table img')

        downloadThreads = []
        for i in range(0, len(comicElem), 2):
                downloadThread = threading.Thread(target = downloadGarfield, args=(comicElem, i, min(len(comicElem), i+2)))
                downloadThreads.append(downloadThread)
                downloadThread.start()

        # Wait for all threads to end.
        for downloadThread in downloadThreads:
                downloadThread.join()
        month + 1
        t + 1
        print('Done')

Tags: theinimageurlforosdownloadres
3条回答

不能将整数连接到字符串,需要先将其转换为字符串

str(month)

如果您需要月份作为int,您可以按照@0tt0和@devReddit回答您

另一方面,您需要定义变量的增量(感谢@Jeppe意识到这一点):

month+=1
t+=1

在这种情况下,您可以将“新”月份定义为str(如果这样更方便的话):

month_s=str(month)

在这种情况下,可以像以前一样使用连接。但是,我建议您按照以下步骤进行操作:

url = f'http://pt.jikos.cz/garfield/{year}/{month_s}'
location = f'Garfield({month_s}-{year})'

int强制转换为str以连接它:

url = 'http://pt.jikos.cz/garfield/' + str(year) + '/' + str(month)

相关问题 更多 >