我正在处理一些返回HTML
字符串(my_html
)的代码。我希望在使用https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser的浏览器中看到它的外观。我刚刚问过这个问题(Scrapy - How to load html string into open_in_browser function),答案告诉我如何将字符串加载到' open_in_browser对象'
headers = {
'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
'upgrade-insecure-requests': "1",
'user-agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36",
'referer': "http://civilinquiry.jud.ct.gov/GetDocket.aspx",
'accept-encoding': "gzip, deflate, sdch",
'accept-language': "en-US,en;q=0.8",
'cache-control': "no-cache",
}
new_response = TextResponse('https://doc.scrapy.org/en/latest/topics/request-response.html#response-objects', headers=headers, body='<html><body>Oh yeah!</body></html>')
open_in_browser(new_response)
然而,现在我看到文本在记事本而不是浏览器(在我的Windows系统上)打开让我觉得系统认为这是一个文本字符串而不是html(即使它有一个外部的html标签):
我怎样才能使这个工作?
编辑:
我将代码更改为
new_response = Response('https://doc.scrapy.org/en/latest/topics/request-response.html#response-objects', headers=headers, body='<html><body>Oh yeah!</body></html>')
现在得到:
TypeError: Unsupported response type: Response
EDIT2:
我意识到在我的scrapy版本(1.1)中,来源是:
def open_in_browser(response, _openfunc=webbrowser.open):
"""Open the given response in a local web browser, populating the <base>
tag for external links to work
"""
from scrapy.http import HtmlResponse, TextResponse
# XXX: this implementation is a bit dirty and could be improved
body = response.body
if isinstance(response, HtmlResponse):
if b'<base' not in body:
repl = '<head><base href="%s">' % response.url
body = body.replace(b'<head>', to_bytes(repl))
ext = '.html'
elif isinstance(response, TextResponse):
ext = '.txt'
else:
raise TypeError("Unsupported response type: %s" %
response.__class__.__name__)
fd, fname = tempfile.mkstemp(ext)
os.write(fd, body)
os.close(fd)
return _openfunc("file://%s" % fname)
我将响应更改为HTMLresponse并开始工作。谢谢
答案 0 :(得分:2)
查看如何定义open_in_browser()
函数:
if isinstance(response, HtmlResponse):
if b'<base' not in body:
repl = '<head><base href="%s">' % response.url
body = body.replace(b'<head>', to_bytes(repl))
ext = '.html'
elif isinstance(response, TextResponse):
ext = '.txt'
else:
raise TypeError("Unsupported response type: %s" %
response.__class__.__name__)
如果获得.txt
,它会创建一个TextResponse
文件 - 这就是为什么你看到记事本用你的HTML打开文件的原因。
相反,您需要初始化常规scrapy.Response
对象并将其传递给open_in_browser()
。
或者,您可以手动创建包含所需内容的临时HTML文件,然后使用file://
协议通过webbrowser.open()
在默认浏览器中打开它。
答案 1 :(得分:0)
这在Python 2.7中对我有效
if (time() - $epoch_time > 5 * 60) { throw new Exception("Message expired") }