【问题标题】:'TypeError: decoding str is not supported' when appending str in for loop within a for loop'TypeError: 不支持解码 str' 在 for 循环内的 for 循环中附加 str 时
【发布时间】:2019-08-15 22:00:34
【问题描述】:

我正在开发一个求职网络抓取工具,但是在将打印语句转换为返回语句时,我遇到了“TypeError:不支持解码 str”,即使此转换公式适用于非循环-within-a-for-loop。

我尝试删除其中一个 str 变量,这很有效,但我需要的是一个包含公司和工作的双重列表

def get_company_and_jobs():
    """this function scrapes the company names 
    and job titles"""
    comps_and_jobs = []
    companyName = pageSoup.find_all('span', class_='company')
    jobTitle = pageSoup.find_all('div', class_='title')
    for span in jobTitle:
        for x in companyName:
            comps_and_jobs.append(str(x.text,span.text))
            # # This is before I added a list
            # print(x.text,span.text)
    return comps_and_jobs
TypeError                                 Traceback (most recent call last)
<ipython-input-60-9bcc02c8c200> in <module>
      4 for span in jobTitle:
      5     for x in companyName:
----> 6             comps_and_jobs.append(str(x.text,span.text))
      7             # # This is before I added a list
      8             # print(x.text,span.text)

TypeError: decoding str is not supported

这是我复制解决方案的相同公式:

def get_company_names():
    """this function scrapes the company names"""
    comp_names = []
    companyName = pageSoup.find_all('span', class_='company')
    for span in companyName:
        comps_names.append(str(span.text))
    ## This is before I added a list
    #     print(span.text)
    return comp_names

有没有更好的方法可以迭代结果以匹配列表或字典中的工作和公司?

我应该为此使用 zip 而不是列表吗?

【问题讨论】:

  • 您将两个参数传递给str。第二个参数(如果存在)是编码说明符,例如'utf-8' 或类似的东西。好像是别的东西。
  • 谢谢@TomKarzes,我添加了我使用的公式并在那里提问。

标签: python-3.x list data-science


【解决方案1】:

因为我传递了两个参数,所以我只是将参数分成两行:

def get_company_and_jobs():
    """this function scrapes the company names 
    and job titles"""
    comps_and_jobs = []
    companyName = pageSoup.find_all('span', class_='company')
    jobTitle = pageSoup.find_all('div', class_='title')
    for span in jobTitle:
        for x in companyName:
            comps_and_jobs.append(str(x.text))
            comps_and_jobs.append(str(span.text))
    return comps_and_jobs

【讨论】:

    猜你喜欢
    • 2017-08-20
    • 2020-02-03
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多