python3 中文乱码
PHP中文网
PHP中文网 2017-04-17 17:34:23
0
2
372
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
import requests

def run():
    soup = requests.get('http://zy.upln.cn/gongshi2014/index.html').text
    soup = BeautifulSoup(soup,'html.parser')
    soup = soup.find('tbody')
    for x in soup.find_all('tr'):
        for y in x.find_all('td'):
            s = y.a.text
            print(s)

if __name__=="__main__":
    run()

读取之后的内容不知道是不是gbk被当成UTF-8来处理了
求教

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
PHPzhong

Personally, it is recommended that when obtaining the response, the string should be parsed according to the encoding format specified in the response

def run():
    r = requests.get('http://zy.upln.cn/gongshi2014/index.html')
    soup = r.text.encode(r.encoding) #这里获取的text先按照指定的字符集解析下,这样gbk、utf8都可以了
    soup = BeautifulSoup(soup, 'html.parser')
    soup = soup.find('tbody')
    for x in soup.find_all('tr'):
        for y in x.find_all('td'):
            s = y.a.text
            print(s)
            

Output

辽宁大学
大连理工大学
沈阳工业大学
沈阳航空航天大学
沈阳理工大学
东北大学
辽宁科技大学
辽宁工程技术大学
辽宁石油化工大学
沈阳化工大学
大连交通大学
大连海事大学
大连工业大学
沈阳建筑大学
辽宁工业大学
沈阳农业大学
大连海洋大学
中国医科大学
辽宁医学院
大连医科大学
辽宁中医药大学
沈阳药科大学
辽宁师范大学
沈阳师范大学
渤海大学
鞍山师范学院
大连外国语大学
东北财经大学
沈阳体育学院
沈阳音乐学院
鲁迅美术学院
辽宁对外经贸学院
沈阳大学
大连大学
辽宁科技学院
沈阳工程学院
辽东学院
大连民族学院
大连理工大学城市学院
沈阳工学院
大连工业大学艺术与信息工程学院
大连科技学院
沈阳城市建设学院
大连医科大学中山学院
辽宁医学院医疗学院
辽宁师范大学海华学院
辽宁理工学院
大连财经学院
沈阳城市学院
大连艺术学院
辽宁何氏医学院
沈阳化工大学科亚学院
大连东软信息学院
辽宁财贸学院
Peter_Zhu

Hello! I've also encountered similar problems.
The solution is to change print(s) to print(s.encode('latin1').decode('utf-8'))
This is the running result:

Good Luck!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!