如何使用BeautifulSoup写入非英语文件

时间:2018-05-29 20:52:42

标签: python python-2.7 unicode web-scraping beautifulsoup

我正在通过BeautifulSoup和Python学习webscraping。我的第一个项目是从cookpad.hu中提取某些食谱。我成功地能够提取,但现在我遇到麻烦,实际上将它们写入文件(csv是我知道该怎么做),由于这个错误:

  

追踪(最近一次通话):   文件“cookpad_scrape.py”,第24行,in      f.writerow(about_clean)   UnicodeEncodeError:'ascii'编解码器无法对位置0中的字符u'\ xe1'进行编码:序数不在范围内(128)

我的代码如下。我在Ubuntu上使用Python 2.7.14。网页的粘贴框为here,但网页本身为this

我假设它不能写匈牙利字母?我确信我会忽略一个非常简单的解决方案。

import requests
from bs4 import BeautifulSoup 
import csv 

'''
Tree of page:
    <div id="recipe main">
        <div id="editor" class="editor">
            <div id="about">
            <section id="ingredients">
            <section id="steps">
'''
#text only: soup.get_text()

page = requests.get('https://cookpad.com/hu/receptek/5040119-parazson-sult-padlizsankrem')
soup = BeautifulSoup(page.text, 'lxml')

f = csv.writer(open('recipes.csv', 'w')) #create and open file in f variable, using 'w' mode
f.writerow(['Recipe 1']) #write top row headings

about = soup.find(id='about')
about_ext = about.p.extract()
about_clean = about_ext.get_text()
f.writerow(about_clean)

ingredients = soup.find(id='ingredients')
ingredients_ext = ingredients.ol.extract()
ingredients_clean = ingredients_ext.find_all(itemprop='ingredients')
#for ingredient in ingredients_clean:

steps = soup.find(id='steps')
steps_p = steps.find_all(itemprop='recipeInstructions')
for step in steps_p:
    extracted = step.p.extract()
    print(extracted.text)
    f.writerow([extracted])

解决方案: 使用python3运行脚本,而不是通过python3 my_script.py

运行脚本

新问题:导出碎片会让我获得良好的步骤结果,但是成分和关于部分的每个字母都以commas分隔。

1 个答案:

答案 0 :(得分:0)

你正在运行python2。在第25行,你要写出'about_clean'变量的内容。您需要对此值进行编码。

f.writerow(about_clean.encode("utf-8"))