使用Python从HTML中提取纯文本

时间:2016-08-14 12:58:09

标签: python beautifulsoup

我正在尝试使用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

2 个答案:

答案 0 :(得分:2)

&#34;错误&#34;是一个警告,并不重要。用soup = BeautifulSoup(k, 'html.parser')

解决问题

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

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

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

答案 1 :(得分:0)

代码上有一个 - 导致错误,&#39; - &#39;非utf-8。在将文本传递给BeautifulSoup之前更改编码可以解决问题。

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