【问题标题】:Download only the text from a webpage content in Python仅从 Python 中的网页内容下载文本
【发布时间】:2015-06-20 07:55:03
【问题描述】:

如何从 Python 网页中下载 text/html/javascript?

我正在尝试获取有关博客作者所写文本的一些统计数据。只需要文本,我想通过避免下载图像等来提高我的程序速度。

我能够将文本与 HTML 标记语言分开。所以我的意图主要是避免在网页中下载额外的内容(如图片、.swf 等)

到目前为止我使用的是:

user_agent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_4; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.63 Safari/534.3'
        headers = {'User-Agent': user_agent}
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req, timeout=60)
content_type = response.info().getheader('Content-Type')
if 'text/html' in content_type:
   return response.read()

但我不确定我做的是否正确(即仅下载文本)

【问题讨论】:

  • 我建议查看 requests 库,以便更轻松地处理 HTTP 请求。

标签: python http urllib2


【解决方案1】:

Python BeautifulSoup 是解析网页的最佳工具之一

import bs4
import urllib.request

webpage=str(urllib.request.urlopen(link).read())
soup = bs4.BeautifulSoup(webpage)

print(soup.get_text())

【讨论】:

  • 出于性能原因,我想这样做(我会更新我的问题。)。因此,我不知道你的答案是否适合我。但是它很有用,所以 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多