【发布时间】:2015-09-26 17:28:22
【问题描述】:
我一直在开发一个程序来浏览我已经保存在文本文件中的各种链接,这些链接主要是夏季机会/营地/等。并刮擦它们,看看是否弹出诸如“奖学金”或“经济援助”之类的关键词。但是,当我运行它时,它给了我上面标题中的错误。
这个问题已经被问过好几次了,但对于不同的人来说似乎是出于不同的原因。因此,我知道可能存在涉及 Unicode 的错误,但我不知道会出现在哪里或为什么会这样。
这是代码:
import BeautifulSoup
import requests
import nltk
file_from = open("links.txt", "r")
list_of_urls = file_from.read().splitlines()
aid_words = ["financial", "aid", "merit", "scholarship"]
count = 0
fin_aid = []
while count <= 10:
for url in list_of_urls:
clean = 1
result = "nothing found"
source = requests.get(url)
plain_text = source.text
soup = BeautifulSoup.BeautifulSoup(plain_text)
print (str(url).upper())
for links in soup.findAll('p', text = True):
tokenized_text = nltk.word_tokenize(links)
for word in tokenized_text:
if word not in aid_words:
print ("not it " + str(clean))
clean += 1
pass
else:
result = str(word)
print (result)
fin_aid.append(url)
break
count += 1
the_golden_book = {"link: ": str(url), "word found: ": str(result)}
fin_aid.append(the_golden_book)
file_to = open("links_with_aid.txt", "w")
file_to.write(str(fin_aid))
file_to.close()
print ("scrape finished")
print (str(fin_aid))
基本上是想从links.txt中取出所有链接,访问前十个(作为测试),在列表“aid_words”中搜索四个单词,以“not it”的形式返回结果以及到目前为止搜索的单词数,如果还没有找到单词,或者如果找到了则检测到的单词(以便我稍后可以访问链接并搜索它,看看它是否是一个误报与否)。
当我通过命令提示符运行它时,这是它在错误消息之前向我显示的内容。
Traceback (most recent call last):
File "finaid.py", line 20, in <module>
soup = BeautifulSoup.BeautifulSoup(plain_text.encode("utf-8"))
File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1522, in __init__
BeautifulStoneSoup.__init__(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1147, in __init__
self._feed(isHTML=isHTML)
File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1189, in _feed
SGMLParser.feed(self, markup)
File "C:\Python27\lib\sgmllib.py", line 104, in feed
self.goahead(0)
File "C:\Python27\lib\sgmllib.py", line 143, in goahead
k = self.parse_endtag(i)
File "C:\Python27\lib\sgmllib.py", line 320, in parse_endtag
self.finish_endtag(tag)
File "C:\Python27\lib\sgmllib.py", line 358, in finish_endtag
method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-9: ordin
al not in range(128)
我在 Python 2.7.10 上运行它,我在 Windows 8.1 上。感谢您的任何帮助,您可以提供!据我所知,它不应该是“link.txt”中的任何内容,这实际上只是同事之前抓取并保存的链接。
【问题讨论】:
-
1.代码和回溯不匹配。显示对应于实际代码的回溯。 2. 不要转储所有代码,创建一个minimal (but complete) code example instead 3. 不相关:在这种情况下避免
str()-- 你的用法要么是错误,要么有更好的替代方案。 -
短答案:使用
python3,长答案:使用文本5年我仍然在python2.x,用户python3中遇到问题 -
当我在 Python 3 上运行它(进行了所有必要的调整)时,它给出了“预期的字符串或缓冲区”,我觉得这更令人困惑。它给出了我使用“word_tokenize”的行的错误。我对 BeautifulSoup 和 nltk 比其他东西更熟悉——有没有办法在不使用这两个的情况下解决这个错误?
-
@alvas:Python 3 可以很容易地检测到一些 Unicode 问题,但它不是小精灵。除非 OP 将学习如何使用 Unicode(第一步:删除可疑的
str()用法);问题不会飞到梦幻岛。
标签: python python-2.7 unicode beautifulsoup nltk