Python简单网页爬虫

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python简单网页爬虫相关的知识,希望对你有一定的参考价值。

由于Python2.x与Python3.x存在很的差异,Python2.x调用urllib用指令urllib.urlopen(),

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

原因是在Python3.X中应该用urllib.request。

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

.open_new_tab(‘baidu.com.html‘)

true

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

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

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

就可以打开了

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)

 

以上是关于Python简单网页爬虫的主要内容,如果未能解决你的问题,请参考以下文章

Python 利用爬虫爬取网页内容 (div节点的疑惑)

爬虫遇到头疼的验证码?Python实战讲解弹窗处理和验证码识别

Python爬虫怎么抓取html网页的代码块

为啥我的python爬虫界面与博主不一样

python爬虫怎么获取动态的网页源码

Python网络爬虫学习手记——爬虫基础