Python简单网页爬虫

因为Python2.x与Python3.x存在很的差别,Python2.x调用urllib用指令urllib.urlopen(),html

运行时报错:AttributeError: module 'urllib' has no attribute 'urlopen'web

缘由是在Python3.X中应该用urllib.request。url

下载网页成功后,调用webbrowsser模块,输入指令webbrowsserspa

.open_new_tab('baidu.com.html')code

truehtm

open('baidu.com.html',‘w’)。write(html)blog

将下载的网页写入指定的目录下,然而下载的网页占0KB,打开显示空白,而后将上代码改成get

open('baidu.com.html',‘wb’)。write(html)it

就能够打开了class

import urllib
>>> import urllib.request
>>> def getHtml(url):
    page = urllib.request.urlopen(url)
    html = page.read()
    return html

>>> import webbrowser
>>> webbrowser.open_new_tab('baidu.com.html')
True
>>> open('baidu.com.html','wb').write(html)
相关文章
相关标签/搜索