Python错误:需要帮助解决2个错误(我是初学者)

2024-04-26 17:25:41 发布

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

我有一个python脚本,通过运行:goodreadsquotes.pyhttps://www.goodreads.com/author/quotes/1791.Seth_Godin>;godin从给定的作者那里下载goodreads的所有引用

但是,我在执行它时遇到了问题,因为我是Python的初学者。目前我有两个错误。代码如下:

from pyquery import PyQuery
import sys, random, re, time


AUTHOR_REX = re.compile('\d+\.(\w+)$')

def grabber(base_url, i=1):
    url = base_url + "?page=" + str(i)
    page = PyQuery(url)
    quotes = page(".quoteText")
    auth_match = re.search(AUTHOR_REX, base_url)
    if auth_match:
      author = re.sub('_', ' ', auth_match.group(1))
    else:
      author = False
    # sys.stderr.write(url + "\n")
    for quote in quotes.items():
        quote = quote.remove('script').text().encode('ascii', 'ignore')
        if author:
          quote = quote.replace(author, " -- " + author)
        print (quote)
        print ('%')

    if not page('.next_page').hasClass('disabled'):
      time.sleep(10)
      grabber(base_url, i + 1)

if __name__ == "__main__":
  grabber(''.join(sys.argv[1:]))

执行后:

py goodreadsquotes.py https://www.goodreads.com/author/quotes/1791.Seth_Godin > godin

误差如下:

Traceback (most recent call last):
  File "goodreadsquotes.py", line 43, in <module>
    grabber(''.join(sys.argv[1:]))
  File "goodreadsquotes.py", line 34, in grabber
    quote = quote.replace(author, " -- " + author)
TypeError: a bytes-like object is required, not 'str'

Tags: pyreauthurlbaseifmatchsys
1条回答
网友
1楼 · 发布于 2024-04-26 17:25:41

从您发布的屏幕截图来看,python中的…encode()方法返回一个bytes对象,因此现在quote不再是字符串,而是bytes对象。因此在quote上调用replace()需要bytes中的参数,而不是str。您可以将author" "+author转换为bytes,如下所示:(第34行)

author_bytes = bytes(author, 'ascii')
replace_string_bytes = bytes(" "+author, 'ascii')
#converted author and the replacement string both to bytes
if author_bytes:
   quote = quote.replace(author_bytes, replace_string_bytes)

相关问题 更多 >