使用spark-submit和BeautifulSoup时出现UnicodeEncodeError

时间:2019-03-05 11:16:15

标签: python python-2.7 apache-spark hadoop beautifulsoup

当我提交作业以引发1.6,hadoop 2.7时,我在Python 2.7中不断收到UnicodeEncodeError,但是当我在pyspark shell上逐行执行相同的代码时,我没有得到相同的错误 >。

我正在使用BeautifulSoup获取所有标签,并使用以下代码行从标签中获取文本:

[r.text for r in BeautifulSoup(line).findAll('ref') if r.text]

我尝试了以下操作:

  1. 设置export PYTHONIOENCODING="utf8"
  2. 使用r.text.encode('ascii', 'ignore')
  3. 也尝试申请sysdefaultencoding('utf-8')

能否请别人告诉我如何解决?下面是错误堆栈:

"/hdata/dev/sdf1/hadoop/yarn/local/usercache/harshdee/appcache/application_1551632819863_0039/container_e36_1551632819863_0039_01_000004/pyspark.zip/pyspark/serializers.py", line 263, in dump_stream
    vs = list(itertools.islice(iterator, batch))
  File "/home/harshdee/get_data.py", line 63, in get_as_row
    return Row(citations=get_citations(line.content), id=line.id, title=line.title)
  File "/home/harshdee/get_data.py", line 47, in get_citations
    refs_in_line = [r.text for r in BeautifulSoup(line).findAll('ref') if r.text]
  File "/usr/lib/python2.7/site-packages/bs4/__init__.py", line 274, in __init__
    self._check_markup_is_url(markup)
  File "/usr/lib/python2.7/site-packages/bs4/__init__.py", line 336, in _check_markup_is_url
    ' that document to Beautiful Soup.' % decoded_markup
  File "/usr/lib64/python2.7/warnings.py", line 29, in _show_warning
    file.write(formatwarning(message, category, filename, lineno, line))
  File "/usr/lib64/python2.7/warnings.py", line 38, in formatwarning
    s =  "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-28: ordinal not in range(128)```

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。我认为问题出在字符串的表示形式上。

为此,我使用了repr函数,该函数返回对象表示形式。换句话说,它基本上会返回经过统一编码的string

我将其应用于line变量。