首页 > 编程 > Python > 正文

python爬虫实战之最简单的网页爬虫教程

2020-02-16 02:03:08
字体:
来源:转载
供稿:网友

前言

网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。最近对python爬虫有了强烈地兴趣,在此分享自己的学习路径,欢迎大家提出建议。我们相互交流,共同进步。话不多说了,来一起看看详细的介绍:

1.开发工具

笔者使用的工具是sublime text3,它的短小精悍(可能男人们都不喜欢这个词)使我十分着迷。推荐大家使用,当然如果你的电脑配置不错,pycharm可能更加适合你。

sublime text3搭建python开发环境推荐查看这篇文章:

[sublime搭建python开发环境][//www.jb51.net/article/51838.htm]

2.爬虫介绍

爬虫顾名思义,就是像虫子一样,爬在Internet这张大网上。如此,我们便可以获取自己想要的东西。

既然要爬在Internet上,那么我们就需要了解URL,法号“统一资源定位器”,小名“链接”。其结构主要由三部分组成:

(1)协议:如我们在网址中常见的HTTP协议。

(2)域名或者IP地址:域名,如:www.baidu.com,IP地址,即将域名解析后对应的IP。

(3)路径:即目录或者文件等。

3.urllib开发最简单的爬虫

(1)urllib简介

Module Introduce
urllib.error Exception classes raised by urllib.request.
urllib.parse Parse URLs into or assemble them from components.
urllib.request Extensible library for opening URLs.
urllib.response Response classes used by urllib.
urllib.robotparser Load a robots.txt file and answer questions about fetchability of other URLs.

(2)开发最简单的爬虫

百度首页简洁大方,很适合我们爬虫。

爬虫代码如下:

from urllib import requestdef visit_baidu(): URL = "http://www.baidu.com" # open the URL req = request.urlopen(URL) # read the URL  html = req.read() # decode the URL to utf-8 html = html.decode("utf_8") print(html)if __name__ == '__main__': visit_baidu()

结果如下图:


我们可以通过在百度首页空白处右击,查看审查元素来和我们的运行结果对比。

当然,request也可以生成一个request对象,这个对象可以用urlopen方法打开。

代码如下:

from urllib import requestdef vists_baidu(): # create a request obkect req = request.Request('http://www.baidu.com') # open the request object response = request.urlopen(req) # read the response  html = response.read() html = html.decode('utf-8') print(html)if __name__ == '__main__': vists_baidu()            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表