簡體   English   中英

為什么我在 Python 中的 def 函數不起作用?

[英]Why is my def function in Python not working?

我正在嘗試將表格中的一些數據保存在 CSV 文件中。

import requests
import csv
from bs4 import BeautifulSoup

#Main function
def getContent(link):
    #Request content
    result1 = requests.get(link)

    #Save source in var
    src1 = result1.content

    #Activate soup
    soup = BeautifulSoup(src1,'lxml')

    #Look for table
    table = soup.find('table')

    #Save in csv
    with open('averageheight.csv','w',newline='') as f:
        writer = csv.writer(f)
        for tr in table('tr'):
            row = [t.get_text(strip=True)for t in tr(['td','th'])]
            writer.writerow(row)


#LINKS
getContent('https://en.wikipedia.org/wiki/Average_human_height_by_country')

我得到的錯誤:

  File "c:/Users/Agent 1/Desktop/Datapackages/Average Height/process.py", line 31, in <module>
    getContent('https://en.wikipedia.org/wiki/Average_human_height_by_country')
  File "c:/Users/Agent 1/Desktop/Datapackages/Average Height/process.py", line 27, in getContent
    writer.writerow(row)
  File "C:\Users\Agent 1\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2044' in position 24: character maps to <undefined>

在我的機器上運行你的代碼並沒有發現錯誤。 但是,您可能需要考慮將encoding='utf-8'指定為with open(...) as f

import requests
import csv
from bs4 import BeautifulSoup

#Main function
def getContent(link):
    #Request content
    result1 = requests.get(link)

    #Save source in var
    src1 = result1.content

    #Activate soup
    soup = BeautifulSoup(src1,'lxml')

    #Look for table
    table = soup.find('table')

    #Save in csv
    with open('averageheight.csv','w',newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        for tr in table('tr'):
            row = [t.get_text(strip=True)for t in tr(['td','th'])]
            writer.writerow(row)


#LINKS
getContent('https://en.wikipedia.org/wiki/Average_human_height_by_country')

將 ascii 字符轉換為utf-8 使用以下修改后的代碼行:

row = [(t.get_text(strip=True)).encode('utf-8') for t in tr(['td','th'])]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM