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

1
2
3
>>> import webbrowser
True

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

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

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

2.读取剪贴板内容:

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

1
2
3
4
5
6
7
#! python3
import webbrowser, sys, pyperclip
if len(sys.argv) > 1:
 mapAddress = ''.join(sys.argv[1:])
else:
 mapAddress = pyperclip.paste()

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

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

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

1
2
3
4
5
6
7
>>> 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()方法可以确保下载确实成功,然后再让程序继续做其他事情。

1
2
3
4
5
6
import requests
try:
 res.raise_for_status()
except Exception as exc:
 print('There was a problem: %s' % (exc))

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

1
2
3
4
5
6
7
8
9
10
>>> 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页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> import requests, bs4
>>> 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'>

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

1
2
3
4
5
6
>>> 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的元素。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> import requests, bs4
>>> 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.通过元素的属性获取数据:接着上面的代码写。

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

python爬取网页数据的更多相关文章

  1. 使用 Python 爬取网页数据

    1. 使用 urllib.request 获取网页 urllib 是 Python 內建的 HTTP 库, 使用 urllib 可以只需要很简单的步骤就能高效采集数据; 配合 Beautiful 等 ...

  2. python爬取网页数据方法

    """#最基本,请求地址无参数# response=urllib.request.urlopen("https://www.scetc.edu.cn" ...

  3. python爬取网页数据并存储到mysql数据库

    #python 3.5 from urllib.request import urlopen from urllib.request import urlretrieve from bs4 impor ...

  4. 如何使用python爬取网页动态数据

    我们在使用python爬取网页数据的时候,会遇到页面的数据是通过js脚本动态加载的情况,这时候我们就得模拟接口请求信息,根据接口返回结果来获取我们想要的数据. 以某电影网站为例:我们要获取到电影名称以 ...

  5. 使用webdriver+urllib爬取网页数据(模拟登陆,过验证码)

    urilib是python的标准库,当我们使用Python爬取网页数据时,往往用的是urllib模块,通过调用urllib模块的urlopen(url)方法返回网页对象,并使用read()方法获得ur ...

  6. python之爬取网页数据总结(一)

    今天尝试使用python,爬取网页数据.因为python是新安装好的,所以要正常运行爬取数据的代码需要提前安装插件.分别为requests    Beautifulsoup4   lxml  三个插件 ...

  7. python爬取网站数据

    开学前接了一个任务,内容是从网上爬取特定属性的数据.正好之前学了python,练练手. 编码问题 因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这个机会算是彻底搞清楚了. 问题要从文字的编码讲 ...

  8. python爬取网页的通用代码框架

    python爬取网页的通用代码框架: def getHTMLText(url):#参数code缺省值为‘utf-8’(编码方式) try: r=requests.get(url,timeout=30) ...

  9. python爬取网站数据保存使用的方法

    这篇文章主要介绍了使用Python从网上爬取特定属性数据保存的方法,其中解决了编码问题和如何使用正则匹配数据的方法,详情看下文     编码问题因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这 ...

随机推荐

  1. C#实现在foreach遍历中删除集合中的元素(方法总结)

    目录 方法一:采用for循环,并且从尾到头遍历 方法二:使用递归 方法三:通过泛型类实现IEnumerator 在foreach中删除元素时,每一次删除都会导致集合的大小和元素索引值发生变化,从而导致 ...

  2. Orleans 初接触(一) 入门例子

    [返回导航] 在简单了解了Orleans 之后我们可以通过几个例子去加深印象 一.Orleans入门例子 这个例子是跟着<Orleans入门例子>(https://www.cnblogs. ...

  3. 【Feign】自定义配置

    [Feign]自定义配置 转载: 自定义配置,如果在同一个工程,注意配置不要和@SpringBootApplication或@ComponentSacan放在用一个包下,就是不要被扫描上 packag ...

  4. java基础篇一

    引言 本人系南京一小小学校的大三小小菜鸟,三年来学了很多杂七杂八的,也荒废了大量的时间,马上就要秋招了,之前也看了不少面试题,备选了一些简单的项目,看了不知多少本的几百页厚的各种知识的pdf电子书,发 ...

  5. Enumeration接口和Iterator接口的区别有哪些?

    Enumeration速度是Iterator的2倍,同时占用更少的内存.但是,Iterator远远比Enumeration安全,因为其他线程不能够修改正在被iterator遍历的集合里面的对象.同时, ...

  6. 用正则表达式【regexp】进行高级搜索数据

    正则表达式介绍 正则表达式是用来匹配文本的特殊字符集合,如果你想从一个文本中提取电话号码而已使用正则表达式,如果你需要查找名字中包含数字的所有文件可以使用正则,如果你你要在文本块中找到所有重复的单词, ...

  7. Python 浮点数的冷知识

    本周的PyCoder's Weekly 上分享了一篇小文章,它里面提到的冷知识很有意思,我稍作补充,分享给大家. 它提到的部分问题,读者们可以先思考下: 若两个元组相等,即 a==b 且 a is b ...

  8. Java实现微信小程序支付(完整版)

    在开发微信小程序支付的功能前,我们先熟悉下微信小程序支付的业务流程图: 不熟悉流程的建议还是仔细阅读微信官方的开发者文档. 一,准备工作 事先需要申请企业版小程序,并开通“微信支付”(即商户功能).并 ...

  9. 常用数据结构之ArrayList

    前言 ArrayList想必是广大Java程序员开发时最常用的数据结构了,但不一定对其原理都有了解,今天我将结合ArrayList的源码对其进行讲解.本文将围绕ArrayList主要特性(包括适用场景 ...

  10. Winform中实现自定义屏保效果(附代码下载)

    场景 效果 注: 博客主页: https://blog.csdn.net/badao_liumang_qizhi 关注公众号 霸道的程序猿 获取编程相关电子书.教程推送与免费下载. 实现 新建form ...