【发布时间】: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