【问题标题】:Extracting plain text from HTML using Python使用 Python 从 HTML 中提取纯文本
【发布时间】:2016-12-20 21:57:05
【问题描述】:

我正在尝试使用 python 从网站中提取纯文本。我的代码是这样的(我在这里找到的稍微修改的版本):

import requests
import urllib
from bs4 import BeautifulSoup
url = "http://www.thelatinlibrary.com/vergil/aen1.shtml"
r = requests.get(url)
k = r.content
file = open('C:\\Users\\Anirudh\\Desktop\\NEW2.txt','w')
soup = BeautifulSoup(k)
for script in soup(["Script","Style"]):
    script.exctract()
text = soup.get_text
file.write(repr(text))

这似乎不起作用。我猜beautifulsoup 不接受r.content。我该怎么做才能解决这个问题?

这是错误 -

UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

The code that caused this warning is on line 8 of the file C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py. To get rid of this warning, change code that looks like this:

 BeautifulSoup([your markup])

to this:

 BeautifulSoup([your markup], "html.parser")

  markup_type=markup_type))
Traceback (most recent call last):
  File "C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py", line 12, in <module>
    file.write(repr(text))
  File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\x97' in position 2130: character maps to <undefined>

Process finished with exit code 1

【问题讨论】:

  • 你得到的错误是什么?
  • @OrDuan 我已将错误编辑到问题中
  • 试试soup = BeautifulSoup(K, 'html.parser') 告诉我错误是否改变。
  • @Harrison,现在是 - Traceback(最近一次调用最后一次):文件“C:/Users/Anirudh/PycharmProjects/untitled/test/__init__.py”,第 12 行,在 file.write(repr(text)) 文件“C:\Python34\lib\encodings\cp1252.py”,第 19 行,编码返回 codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap ' codec can't encode character '\x97' in position 2130: character maps to 哦,顺便说一句,当你包含 html.parser 时,那个警告是什么?发生了什么?
  • @AnirudhGanesh 如果您查看错误消息,它会告诉您它无法编码此字符codetable.net/hex/97

标签: python beautifulsoup


【解决方案1】:

“错误”是一个警告,没有任何后果。用soup = BeautifulSoup(k, 'html.parser') 让它安静下来

script.exctract() 似乎有一个错字extract 这个词拼写错误。

实际的错误似乎是内容是字节串,但您是在文本模式下编写。源包含一个破折号。处理这个字符是个问题。

您可以使用soup.encode("utf-8") 进行编码。这意味着将编码硬编码到您的脚本中(这很糟糕)。或者尝试对文件 open(..., 'wb') 使用二进制模式,或者在将内容传递给 Beautiful Soup 之前将内容转换为字符串,使用该文件的正确编码,使用 k = str(r.content,"utf-8")。

【讨论】:

  • 仍然是同样的错误,错误更正并使用 repr(k)
  • 在传递给美丽的汤之前可能会转换为字符串。
  • 对不起,我想我误解了,但 str(k) 也无济于事。我按照你的回答做了,结果还是一样
  • 你能用print 代替file.write 吗?
  • 我好像修好了,代码应该是soup.get_text()
【解决方案2】:

代码上有一个 - 导致错误,'-' 不是 utf-8 。在将文本传递给 BeautifulSoup 之前更改编码解决了这个问题。

另一个错误是由于 soup.get_text 引起的。 Missing out() 暗示我引用的是方法,而不是输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2015-11-05
    • 1970-01-01
    • 2018-12-08
    相关资源
    最近更新 更多