实例讲解Python爬取网页数据


Posted in Python onJuly 08, 2018

一、利用webbrowser.open()打开一个网站:

>>> import webbrowser 
>>> webbrowser.open('http://i.firefoxchina.cn/?from=worldindex') 
True

实例:使用脚本打开一个网页。

所有Python程序的第一行都应以#!python开头,它告诉计算机想让Python来执行这个程序。(我没带这行试了试,也可以,可能这是一种规范吧)

1.从sys.argv读取命令行参数:打开一个新的文件编辑器窗口,输入下面的代码,将其保存为map.py。

2.读取剪贴板内容:

3.调用webbrowser.open()函数打开外部浏览:

#! python3 
import webbrowser, sys, pyperclip 
if len(sys.argv) > 1: 
 mapAddress = ''.join(sys.argv[1:]) 
else: 
 mapAddress = pyperclip.paste() 
webbrowser.open('http://map.baidu.com/?newmap=1&ie=utf-8&s=s%26wd%3D' + mapAddress

注:不清楚sys.argv用法的,请参考这里;不清楚.join()用法的,请参考这里。sys.argv是字符串的列表,所以将它传递给join()方法返回一个字符串。

好了,现在选中'天安门广场'这几个字并复制,然后到桌面双击你的程序。当然你也可以在命令行找到你的程序,然后输入地点。

二、用requests模块从Web下载文件:requests模块不是Python自带的,通过命令行运行pip install request安装。没翻墙是很难安装成功的,手动安装可以参考这里。

>>> import requests 
>>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') #向get中传入一个网址 
>>> type(res) #响应对象 
<class 'requests.models.Response'> 
>>> print(res.status_code) #响应码 
200 
>>> res.text #返回的文本

requests中查看网上下载的文件内容的方法还有很多,如果以后的博客用的到,会做说明,在此不再一一介绍。在下载文件的过程中,用raise_for_status()方法可以确保下载确实成功,然后再让程序继续做其他事情。

import requests 
res = requests.get('http://i.firefoxchina.cn/?from=worldindex') 
try: 
 res.raise_for_status() 
except Exception as exc: 
 print('There was a problem: %s' % (exc))

三、将下载的文件保存到本地:

>>> import requests 
>>> res = requests.get('http://tech.firefox.sina.com/17/0820/10/6DKQALVRW5JHGE1I.html##0-tsina-1-13074-397232819ff9a47a7b7e80a40613cfe1') 
>>> res.raise_for_status() 
>>> file = open('1.txt', 'wb') #以写二进制模式打开文件,目的是保存文本中的“Unicode编码” 
>>> for word in res.iter_content(100000): #<span class="fontstyle0"><span class="fontstyle0">iter_content()</span><span class="fontstyle1">方法在循环的每次迭代中返回一段</span><span class="fontstyle0">bytes</span><span class="fontstyle1">数据</span><span class="fontstyle1">类型的内容,你需要指定其包含的字节数</span></span> 
 file.write(word) 
 
 
16997 
>>> file.close()

四、用BeautifulSoup模块解析HTML:在命令行中用pip install beautifulsoup4安装它。
1.bs4.BeautifulSoup()函数可以解析HTML网站链接requests.get(),也可以解析本地保存的HTML文件,直接open()一个本地HTML页面。

>>> import requests, bs4 
>>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') 
>>> res.raise_for_status() 
>>> soup = bs4.BeautifulSoup(res.text) 
 
Warning (from warnings module): 
 File "C:\Users\King\AppData\Local\Programs\Python\Python36-32\lib\site-packages\beautifulsoup4-4.6.0-py3.6.egg\bs4\__init__.py", line 181 
 markup_type=markup_type)) 
UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently. 
 
The code that caused this warning is on line 1 of the file <string>. To get rid of this warning, change code that looks like this: 
 
 BeautifulSoup(YOUR_MARKUP}) 
 
to this: 
 
 BeautifulSoup(YOUR_MARKUP, "html.parser") 
 
>>> soup = bs4.BeautifulSoup(res.text, 'html.parser') 
>>> type(soup) 
<class 'bs4.BeautifulSoup'>

我这里有错误提示,所以加了第二个参数。

>>> import bs4 
>>> html = open('C:\\Users\\King\\Desktop\\1.htm') 
>>> exampleSoup = bs4.BeautifulSoup(html) 
>>> exampleSoup = bs4.BeautifulSoup(html, 'html.parser') 
>>> type(exampleSoup) 
<class 'bs4.BeautifulSoup'>

2.用select()方法寻找元素:需传入一个字符串作为CSS“选择器”来取得Web页面相应元素,例如:
soup.select('div'):所有名为<div>的元素;

soup.select('#author'):带有id属性为author的元素;

soup.select('.notice'):所有使用CSS class属性名为notice的元素;

soup.select('div span'):所有在<div>元素之内的<span>元素;

soup.select('input[name]'):所有名为<input>并有一个name属性,其值无所谓的元素;

soup.select('input[type="button"]'):所有名为<input>并有一个type属性,其值为button的元素。

想查看更多的解析器,请参看这里。

>>> import requests, bs4 
>>> res = requests.get('http://i.firefoxchina.cn/?from=worldindex') 
>>> res.raise_for_status() 
>>> soup = bs4.BeautifulSoup(res.text, 'html.parser') 
>>> author = soup.select('#author') 
>>> print(author) 
[] 
>>> type(author) 
<class 'list'> 
>>> link = soup.select('link ') 
>>> print(link) 
[<link href="css/mozMainStyle-min.css?v=20170705" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/>, <link href="" id=" rel="external nofollow" rel="external nofollow" rel="external nofollow" moz-skin" rel="stylesheet" type="text/css"/>, <link href="" id=" rel="external nofollow" rel="external nofollow" rel="external nofollow" moz-dir" rel="stylesheet" type="text/css"/>, <link href="" id=" rel="external nofollow" rel="external nofollow" rel="external nofollow" moz-ver" rel="stylesheet" type="text/css"/>] 
>>> type(link) 
<class 'list'> 
>>> len(link) 
4 
>>> type(link[0]) 
<class 'bs4.element.Tag'> 
>>> link[0] 
<link href="css/mozMainStyle-min.css?v=20170705" rel="external nofollow" rel="external nofollow" rel="stylesheet" type="text/css"/> 
>>> link[0].attrs 
{'rel': ['stylesheet'], 'type': 'text/css', 'href': 'css/mozMainStyle-min.css?v=20170705'}

 3.通过元素的属性获取数据:接着上面的代码写。

>>> link[0].get('href') 
'css/mozMainStyle-min.css?v=20170705

上面这些方法也算是对“网络爬虫”的一些初探。

Python 相关文章推荐
Python算法之栈(stack)的实现
Aug 18 Python
python的re模块应用实例
Sep 26 Python
Python通过RabbitMQ服务器实现交换机功能的实例教程
Jun 29 Python
centos 安装python3.6环境并配置虚拟环境的详细教程
Feb 22 Python
windows下cx_Freeze生成Python可执行程序的详细步骤
Oct 09 Python
为什么str(float)在Python 3中比Python 2返回更多的数字
Oct 16 Python
Python实现高斯函数的三维显示方法
Dec 29 Python
Python函数参数类型及排序原理总结
Dec 19 Python
Python:__eq__和__str__函数的使用示例
Sep 26 Python
PyCharm最新激活码(2020/10/27全网最新)
Oct 27 Python
详解python3 GUI刷屏器(附源码)
Feb 18 Python
python调试工具Birdseye的使用教程
May 25 Python
python十进制和二进制的转换方法(含浮点数)
Jul 07 #Python
Python3+django2.0+apache2+ubuntu14部署网站上线的方法
Jul 07 #Python
python3实现字符串的全排列的方法(无重复字符)
Jul 07 #Python
python3 kmp 字符串匹配的方法
Jul 07 #Python
vue.js实现输入框输入值内容实时响应变化示例
Jul 07 #Python
详解Python最长公共子串和最长公共子序列的实现
Jul 07 #Python
python求最大连续子数组的和
Jul 07 #Python
You might like
ThinkPHP之getField详解
2014/06/20 PHP
php给图片加文字水印
2015/07/31 PHP
PHP不使用递归的无限级分类简单实例
2016/11/05 PHP
PHP四种排序算法实现及效率分析【冒泡排序,插入排序,选择排序和快速排序】
2018/04/27 PHP
thinkPHP中U方法加密传递参数功能示例
2018/05/29 PHP
些很实用且必用的小脚本代码
2006/06/26 Javascript
JQuery this 和 $(this) 的区别
2009/08/23 Javascript
利用javascript数组长度循环数组内所有元素
2013/12/27 Javascript
jQuery元素选择器用法实例
2014/12/23 Javascript
jQuery中mouseover事件用法实例
2014/12/26 Javascript
javascript搜索框效果实现方法
2015/05/14 Javascript
JavaScript仿微博输入框效果(案例分析)
2016/12/06 Javascript
JavaScript实现弹窗效果代码分析
2017/03/09 Javascript
JavaScript调试之console.log调试的一个小技巧分享
2017/08/07 Javascript
基于Vue 2.0的模块化前端 UI 组件库小结
2017/12/21 Javascript
详解微信小程序与内嵌网页交互实现支付功能
2018/10/22 Javascript
[02:40]DOTA2超级联赛专访430 从小就爱玩对抗性游戏
2013/06/18 DOTA
Python专用方法与迭代机制实例分析
2014/09/15 Python
基python实现多线程网页爬虫
2015/09/06 Python
python实现画圆功能
2018/01/25 Python
Python初学者需要注意的事项小结(python2与python3)
2018/09/26 Python
解决python3 pika之连接断开的问题
2018/12/18 Python
django实现类似触发器的功能
2019/11/15 Python
英国领先的品牌珠宝和配件供应商:Acotis Jewellery
2018/03/07 全球购物
Aurora London官网:奢华、负担得起的皮革手袋
2020/08/01 全球购物
linux面试题参考答案(10)
2016/10/26 面试题
怎样写演讲稿
2014/01/04 职场文书
高中微机老师自我鉴定
2014/02/16 职场文书
入党积极分子自我鉴定
2014/02/18 职场文书
农民工工资承诺书范文
2014/03/31 职场文书
市场营销工作计划书
2014/05/06 职场文书
小学师德师风整改措施
2014/10/27 职场文书
2015入党个人自传范文
2015/06/26 职场文书
解决python绘图使用subplots出现标题重叠的问题
2021/04/30 Python
python文本处理的方案(结巴分词并去除符号)
2021/05/26 Python
超越Nginx的Web服务器caddy优雅用法
2022/06/21 Servers