为什么从页面中检索的文本有时看起来像胡言乱语? [英] Why does text retrieved from pages sometimes look like gibberish?

查看:19
本文介绍了为什么从页面中检索的文本有时看起来像胡言乱语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中使用 urllib 和 urllib2 打开和阅读网页,但有时,我得到的文本不可读.例如,如果我运行这个:

I'm using urllib and urllib2 in Python to open and read webpages but sometimes, the text I get is unreadable. For example, if I run this:

import urllib

text = urllib.urlopen('http://tagger.steve.museum/steve/object/141913').read()
print text

我收到一些无法阅读的文本.我读过这些帖子:

I get some unreadable text. I've read these posts:

来自 urlopen 的胡言乱语

python urllib2 是否自动解压 gzip 数据从网页获取?

但似乎找不到我的答案.

but can't seem to find my answer.

预先感谢您的帮助!

更新:我通过说服"服务器我的用户代理是浏览器而不是爬虫来解决这个问题.

UPDATE: I fixed the problem by 'convincing' the server that my user-agent is a brower and not a crawler.

import urllib

class NewOpener(urllib.FancyURLopener):
  version = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.120 Chrome/15.0.874.120 Safari/535.2'

nop = NewOpener()
html_text = nop.open('http://tagger.steve.museum/steve/object/141913').read()

感谢大家的回复.

推荐答案

您可以使用 Selenium 来获取内容.下载服务器和客户端驱动程序,运行服务器并运行:

You can use Selenium to get the content. Download the server and client drivers, run server and run this:

from selenium import selenium
s = selenium("localhost", 4444, "*chrome", "http://tagger.steve.museum")
s.start()

s.open("/steve/object/141913")

text = s.get_html_source()
print text

这篇关于为什么从页面中检索的文本有时看起来像胡言乱语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆