我有一个简单的脚本来从公共站点抓取一些信息,然后将数据附加到 CSV 文件中:
import requests
import base64
import csv
from lxml import html
from lxml import etree
print (csv.list_dialects())
startUrl = "http://example.com?page="
#max. 964
for i in range (1,20):
print (i)
page = requests.get(startUrl+str(i))
tree = html.fromstring(page.content)
for element in tree.xpath('//*[@class="std-link std-link--unobtrusive std-link--visitable std-bold"]/@href'):
subpage = requests.get(element)
subtree = html.fromstring(subpage.content)
study = subtree.xpath('//*[@class="std-profileHero__headline"]/h1/text()')
uni = subtree.xpath('//*[@class="std-headline std-headline--h3"]/a/text()')
if study:
study = study[0].replace("\n"," ").replace("\t"," ")
study = str(study.encode("utf-8")).strip()
else:
study = "-"
if uni:
uni = uni[0].replace("\n"," ").replace("\t"," ")
uni = str(uni.encode("utf-8")).strip()
else:
uni = "-"
with open("results.csv", "a", newline="", encoding="utf-8") as csv_file:
writer = csv.writer(csv_file, delimiter=";")
writer.writerow([uni, study])
该脚本有效,但存储在 CSV 中的信息存在编码问题,因此我得到如下值:
当我在 MS Excel 2016 中打开 CSV 时,这些值会保留。
如您所见,脚本对字符串进行编码:.encode("utf-8")
. 我还确保 CSF 文件已编码:encoding="utf-8"
.
我尝试不使用该encode()
功能,但随后编码在德语字符(如ü、ä等)上被破坏。
我究竟做错了什么?
出现奇怪值的原因是您使用的是str(b'bytes')
而不是str(b'bytes', encoding)
,它的作用类似于repr(b'bytes')
并给您"b'bytes'"
而不是"bytes"
。
因此,您应该完全对对象进行操作,或者完全对str
对象进行操作bytes
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句