【问题标题】:how to get raw html text of a given url using python如何使用python获取给定url的原始html文本
【发布时间】:2015-04-21 00:59:59
【问题描述】:

我在 python 中使用 html2text 通过获取任何 URL 来获取 HTML 页面的原始文本(包括标签),但出现错误。

我的代码 -

import html2text
import urllib2

proxy = urllib2.ProxyHandler({'http': 'http://<proxy>:<pass>@<ip>:<port>'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)
html = urllib2.urlopen("http://www.ndtv.com/india-news/this-stunt-for-a-facebook-like-got-the-hyderabad-youth-arrested-740851").read()
print html2text.html2text(html)

错误——

Traceback (most recent call last):
  File "t.py", line 8, in <module>
    html = urllib2.urlopen("http://www.ndtv.com/india-news/this-stunt-for-a-facebook-like-got-the-hyderabad-youth-arrested-740851").read()
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 404, in open
    response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 422, in _open
    '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1214, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 110] Connection timed out>

谁能解释我做错了什么?

【问题讨论】:

  • 这和html2text没有任何关系;这是 URL 提取中的错误。您可以通过浏览器加载该 URL 吗?你能再试一次吗?像这样的网络错误通常是间歇性的。
  • 是的,它在浏览器上运行良好......任何其他建议......??
  • urllib2.urlopen 已经为您提供了文本;这个错误我不知道。
  • 这个错误意味着你的脚本等待了很长时间但是服务器没有说什么。
  • 您需要改进拼写和大小写。我被禁止了一次。

标签: python html


【解决方案1】:

如果您不需要 SSL,Python 2.7.x 中的这个脚本应该可以工作:

import urllib
url = "http://stackoverflow.com"
f = urllib.urlopen(url)
print f.read()

Python 3.x 中使用urllib.request 而不是urllib

因为urllib2 用于 Python 2,所以在 Python 3 中它被合并到了urllib

http:// 为必填项。

编辑: 2020 年,您应该使用第 3 方模块 requestsrequests可以和pip一起安装。

import requests
print(requests.get("http://stackoverflow.com").text)

【讨论】:

  • 对不起,但它没有帮助它给出了同样的错误......你还有其他解决方案吗......??
猜你喜欢
  • 2012-03-18
  • 2012-07-12
  • 2020-12-16
  • 1970-01-01
  • 2022-12-03
  • 2014-08-21
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多