爬虫时网页显示的正常中文,源代码却乱了

初学python不久,在用selenium爬实习僧的网站时(搜索奔驰),再用开发者工具看源代码,是这样的
图片描述

源网页是正常的:
clipboard.png

读取这个网页的代码是这样的(小部分):

def get_products():

"""
提取商品数据
"""
#page_source属于str格式
html = browser.page_source
doc = pq(html)
items = doc('.position .position-list li.font').items()
for item in items:
    product = {
        'name': item.find('.name').text(),
        'release_time': item.find('.release-time').text(),
        'company': item.find('.company').text(),
        'area': item.find('.area').text(),
        'info': item.find('.more').text(),
    }
    print(product)
    

然后在spyder(用的anaconda3)的控制台中的输出是这样的,其中上面截图对应的是‘info’的信息

{'name': 'ue222uee04uf627 uf627uee14uee14uebe3ue321ue817 实习ue194', 'release_time': '2天前', 'company': '戴姆勒奔驰', 'area': '北京', 'info': 'ue83buf591uf591-ue83buf825uf591/天|uf825天/周|uecb6个月'}

之后写入txt文件,用了utf8编码,发现还是一个样子。
代码:

def save_to_text(product):

file = word + '.txt'
with open(file, 'a' , encoding='utf-8') as k:
    for key, value in product.items():
        k.write(key + ':' + value + '\n')

打开文件:
name:  实习
release_time:2天前
company:戴姆勒奔驰
area:北京
info:-/天|天/周|个月

所以到底还是编码的问题么?

阅读 3.1k
3 个回答

字体反爬虫,需要单独解析字体

反爬了,你如果只是想练习的话换个网站爬

尝试获取网页的编码 然后对结果进行解码在重新编码

url = 'http://www.cea.gov.cn/publish...'
result = requests.get(url=url)
print(result.encoding) # <-- 获取网页编码格式

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题