栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

解决python遇到Unicode字符无法输出到ANSI编码文本的小技巧

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决python遇到Unicode字符无法输出到ANSI编码文本的小技巧

#coding:gbk
from selenium import webdriver
from selenium.webdriver.common import options
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By 
import time

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(executable_path ="chromedriver",options=options)
driver.get("https://liquicity.com/artists/")
time.sleep(1)
num=-1
while True:
    try:
        num+=1
        artists=driver.find_elements(By.CLASS_NAME,'elementor-button-text')[num].text
        print(artists)
        with open("liquicity_artists.txt","a") as f:
            if num == 22 :
                f.write("Ella Noeln")
            else:
                f.write(artists+"n")
    except:
        break

先看看是哪一行有Unicode字符,发现是第22行。那么写一个if判断到22行时就输出修改过的字母追加到文本就行。

with open("liquicity_artists.txt","a") as f:
        if num == 22 :
            f.write("Ella Noeln")
        else:
            f.write(artists+"n")

这里的open用的a参数,这样就可以追加文本,而不是替换文本之前的内容。

结果正常导出到txt,编码也是ANSI码。
不过这种方法适合于我这种爬取数据少的情况下,其实更简单直接复制控制台里面的输出的内容过去到文本里面改也可以。

参考文献:
python selenium while 循环

【python】读取和输出到txt

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339626.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号