擅长:python、mysql、java
<p>我找到了最好的一段代码,可以在不使用javascript或不需要的情况下提取文本:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract() # rip it out
# get text
text = soup.get_text()
# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)
print(text)
</code></pre>
<p>你只需要在以下之前安装美偶:</p>
<pre><code>pip install beautifulsoup4
</code></pre>