我在这里阅读了很多关于此的帖子,但总体而言我对 Python 还很陌生,所以我希望获得更多信息。
本质上,我正在尝试编写一些东西,从网站中提取单词定义并将它们写入文件。我一直在使用 BeautifulSoup,并且取得了相当大的进步,但这是我的问题 -
from __future__ import print_function
import requests
import urllib2, urllib
from BeautifulSoup import BeautifulSoup
wordlist = open('test.txt', 'a')
word = raw_input('Paste your word ')
url = 'http://services.aonaware.com/DictService/Default.aspx?action=define&dict=wn&query=%s' % word
# print url
html = urllib.urlopen(url).read()
# print html
soup = BeautifulSoup(html)
visible_text = soup.find('pre')(text=True)
print(visible_text, file=wordlist)
这似乎是我需要的,但以这种格式放置
[u'passable\n adj 1: able to be passed or traversed or crossed; "the road is\n passable"
但我需要它是纯文本的。我试过使用 sanitizer (我通过漂白剂运行它,但没有用。我在这里阅读了其他一些答案,但他们没有解释代码的工作原理,我不想如果我不明白它是如何工作的,请添加一些东西。
有什么办法只拉明文吗?
编辑:我最终做了
from __future__ import print_function
import requests
import urllib2, urllib
from bs4 import BeautifulSoup
wordlist = open('test.txt', 'a')
word = raw_input('Paste your word ')
url = 'http://services.aonaware.com/DictService/Default.aspx?action=define&dict=wn&query=%s' % word
# print url
html = urllib.urlopen(url).read()
# print html
soup = BeautifulSoup(html)
visible_text = soup.find('pre')(text=True)[0]
print(visible_text, file=wordlist)
请您参考如下方法:
代码已经给了你 plaintext , 它恰好有一些字符编码为 entity references .在这种情况下,构成 XML/HTML 语法一部分的特殊字符被编码以防止它们破坏文本的结构。
要解码它们,请使用 HTMLParser 模块:
import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('"the road is passable"')
>>> u'"the road is passable"'
