获取错误“ TypeError:预期的字符串或类似字节的对象”

时间:2019-01-09 11:32:29

标签: python byte typeerror

我正在使用Python3,并且在我的代码中出现以下错误。尝试下载pdf并存储在本地目录中

r_l = 'https://www.ccc.com'
class Data:

    def getlk(self, url):
        all_links = []
        page = requests.get(url)
        soup = BeautifulSoup(page.text, 'html.parser')
        for href in soup.find_all(class_='omrlist'):
            all_links.append(root_url + href.find('a').get('href'))
        return all_links

    def getmth_lk(self, ylk):
        rpLk = []
        for url in ylk:
            links = self.getlk(url)
            reportLinks.append(links)


            for url_ in links:
                if ".pdf" in url_:
                    if "Annual" not in url_:
                        lastindex = url_.rfind('/')
                        strlen = len(url_)
                        filename = url_[lastindex:strlen].replace("/", "")

                        file = pathlib.Path('/home/' + filename)
                        if not file.exists():
                            urllib.request.urlretrieve(rpLk, str(filename))


if __name__ == '__main__':
    obj = Data()
    yLk = obj.getlk(r_l + '/oil/reports/')
    mth_lk = obj.getmth_lk(yLk)

我尝试了上面的代码,但错误正在出现

Traceback (most recent call last):
  File "/home/dwnpdf-to-dir.py", line 248, in <module>
    mth_lk = obj.getmth_lk(yLk)
  File "/home/dwnpdf-to-dir.py", line 228, in getmth_lk
    urllib.request.urlretrieve(rpLk, str(filename))
  File "/usr/lib/python3.5/urllib/request.py", line 186, in urlretrieve
    url_type, path = splittype(url)
  File "/usr/lib/python3.5/urllib/parse.py", line 861, in splittype
    match = _typeprog.match(url)
TypeError: expected string or bytes-like object

上述错误即将到来,请指导我克服此错误

1 个答案:

答案 0 :(得分:0)

正如错误中所述,urlretrievestring or bytes-like object作为第一个位置参数。但是rpLk是一个列表。

您是否宁愿通过url_作为参数?

您是否正在尝试下载文件?我认为您应该改用urllib.request.urlopen