问题 如何使用python获取给定URL的原始html文本


我在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>

谁能解释我做错了什么?


11776
2018-02-19 15:41


起源

这与html2text没有任何关系;这是URL提取中的错误。你可以通过浏览器加载该URL吗?你能再试一次吗?像这样的网络错误通常是间歇性的。 - Tom Hunt
是的,它在浏览器上工作得很好....任何其他暗示.. ?? - aquaman
urllib2.urlopen已经为你提供了文字;那个错误我不知道。 - noɥʇʎԀʎzɐɹƆ
该错误意味着您的脚本等了很长时间但服务器没有说什么。 - noɥʇʎԀʎzɐɹƆ
您需要提高拼写和大小写。我被禁止了一次。 - noɥʇʎԀʎzɐɹƆ


答案:


如果您不需要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:// 是必须的。


10
2018-02-19 17:54



抱歉,但它没有帮助它给出同样的错误....你有任何其他解决方案.. ?? - aquaman
@aquaman试试 urllib.request.urlopen(url) - codingninja