【问题标题】:Python ignore character and print next character from list in for loopPython忽略字符并在for循环中从列表中打印下一个字符
【发布时间】:2017-02-09 20:26:34
【问题描述】:

我正在使用 BeautifulSoup4 并请求从网站上抓取信息。

然后我将所需的信息存储在列表中,我从页面中抓取的两种不同类型的信息有两个列表。

    try:
        for i in range(0,1000):
            location = dive_data1[((9*i)-7)].text
            locations.append(location)
            location = dive_data2[((9*i)-7)]
            locations.append(location)
            depth = dive_data1[((9*i)-6)].text
            depths.append(depth)
            depth = dive_data2[((9*i)-6)].text
            depths.append(depth)

    except:
        pass

之后,我尝试将这些列表传递到另一个 for 循环中,以将内容写入 CSV 文件。

    try:
        writer = csv.writer(dive_log)
        writer.writerow( ("Locations and depths") )
        writer.writerow( ("Sourced from:", str(url_page)) )
        writer.writerow( ("Location", "Depth") )
        for i in range(len(locations)):
            writer.writerow( (locations[i], depths[i]) )

当我运行脚本时,我收到此错误:

writer.writerow( (locations[i], depths[i]) )
UnicodeEncodeError: 'ascii' codec can't encode characters in position 65-66:      ordinal not in range(128)

我试过这个来传递它无法编码的字符:

    writer = csv.writer(dive_log)
    writer.writerow( ("Locations and depths") )
    writer.writerow( ("Sourced from:", str(url_page)) )
    writer.writerow( ("Location", "Depth") )
    for i in range(len(locations)):
        try:
            writer.writerow( (locations[i], depths[i]) )

        except:
            pass

当我运行它时,只有在 for 循环之前的行被执行,它完全通过了 for 循环的重复。

我的脚本中的全部代码被复制到下面,以防它与我在其余部分中没有看到的内容相关。

import csv
from bs4 import BeautifulSoup
import requests

dive_log = open("divelog.csv", "wt")
url_page = "https://en.divelogs.de/log/Mark_Gosling"
r = requests.get(url_page)
soup = BeautifulSoup(r.content)

dive_data1 = soup.find_all("tr", {"class": "td2"})
dive_data2 = soup.find_all("td", {"class": "td"})
locations = []
depths = []

try:
    for i in range(0,1000):
        location = dive_data1[((9*i)-7)].text
        locations.append(location)
        location = dive_data2[((9*i)-7)]
        locations.append(location)
        depth = dive_data1[((9*i)-6)].text
        depths.append(depth)
        depth = dive_data2[((9*i)-6)].text
        depths.append(depth)

except:
    pass

try:
    writer = csv.writer(dive_log)
    writer.writerow( ("Locations and depths") )
    writer.writerow( ("Sourced from:", str(url_page)) )
    writer.writerow( ("Location", "Depth") )
    for i in range(len(locations)):
        try:
            writer.writerow( (locations[i], depths[i]) )

        except:
            pass

finally:
    dive_log.close()

print open("divelog.csv", "rt").read()
print "\n\n"
print locations

【问题讨论】:

  • 这应该可以处理无法编码的字符:soup = BeautifulSoup(response.content.decode('utf-8', 'ignore'))
  • 除非您可以丢失数据,否则不要忽略任何内容,找出要使用的正确编码然后使用它。数据也是 utf-8 编码的,所以问题出在其他地方。也不要使用一揽子例外,捕捉你所期望的并记录/打印错误。

标签: python beautifulsoup export-to-csv


【解决方案1】:

你在写的时候需要在循环中编码成utf-8:

for i in range(len(locations)):
        writer.writerow((locations[i].encode("utf-8"), depths[i].encode("utf-8")) )

【讨论】:

    【解决方案2】:

    就像@yedpodtriztko 指出的那样。您可以将无法解码的字符保留为:

    而不是做:

    soup = BeautifulSoup(r.content)
    

    你可以用这个:

    soup = BeautifulSoup(r.content.decode('utf-8', 'ignore'))
    

    【讨论】:

      猜你喜欢
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2021-02-24
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 2011-09-07
      相关资源
      最近更新 更多