【问题标题】:Python3 encoding issuesPython3 编码问题
【发布时间】:2017-06-19 02:35:39
【问题描述】:

我正在学习用python3爬行。 我只想从 html 代码中提取文本。

ex) 在 html 中

<div class='titleArea'>
    "~~~~~ text~~~~"
</div>

所以,我写了这段代码来提取文本

    title_temp = soup.findAll('div',class_='titleArea')
    print(title_temp)

** 我知道 print(title_temp[0].text) 但没关系

结果是

这张图片的内容是

[<div class='titleArea'>
        @#$!$^!@#!@^#!$^!@#!@#!@# 
</div>]
[<div class='titleArea'>
        @#$!$^!@#!@^#!$^!@#!@#!@# 
</div>]

***有两个List的原因是重复的。

我不想要那个文本。

我该怎么办?

我认为是 utf-8 的问题。

对吗?

所以,

我写的

# -*- coding: utf-8 -*-

但是,没有效果。

【问题讨论】:

  • 张贴网址并请求代码
  • “我不想要那个文本”是什么意思。 ?请发布您想要的确切输出?
  • url 是 hri.co.kr/board/…,我想精确地确定每个帖子的标题唯一的 '~~~~~ text~~~~'

标签: python python-3.x web-crawler utf


【解决方案1】:
import requests, bs4

r = requests.get('http://hri.co.kr/board/reportView.asp?firstDepth=1&secondDepth=1&numIdx=26865')
r.encoding='euc-kr'
soup = bs4.BeautifulSoup(r.text, 'lxml')
soup.find_all('div',class_='titleArea')

出来:

[<div class="titleArea">
                                트럼프노믹스가 중국 경제에 미치는 영향
                             </div>]

chartset 在 html 头标签中:

编辑: 更优雅的方式:

import requests, bs4

r = requests.get('http://hri.co.kr/board/reportView.asp?firstDepth=1&secondDepth=1&numIdx=26865')
r.encoding = r.apparent_encoding

这将自动设置编码。

【讨论】:

  • 哦!!!!!!!!!!!!!!!非常非常非常非常感谢!!!!!!!!!!这是一个很大的帮助。我有一张便条,记录了一些重要的事情。我会把这个写在便条上。非常非常非常非常非常感谢
  • @Good answer buddy!
  • @Good~~~ 绝对的~~谢谢
  • @我查过了!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 1970-01-01
  • 2018-06-06
相关资源
最近更新 更多