【发布时间】: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