从Web抓取信息

时间:2023-03-10 04:10:15
从Web抓取信息

来源:python编程快速上手——Al Sweigart

webbrowser:是 Python 自带的,打开浏览器获取指定页面。

requests:从因特网上下载文件和网页。

Beautiful Soup:解析 HTML,即网页编写的格式。

selenium:启动并控制一个 Web 浏览器。 selenium 能够填写表单,并模拟鼠标在这个浏览器中点击。

1 利用 Webbrowser 模块

webbrowser 模块的 open()函数可以启动一个新浏览器,打开指定的 URL。 Web 浏览器的选项卡将打开 URL http://inventwithpython.com/。这大概就是webbrowser 模块能做的唯一的事情。

建立以下程序:

• 从 sys.argv 读取命令行参数。
• 读取剪贴板内容。
• 调用 webbrowser.open()函数打开外部浏览器

 import webbrowser, sys, pyperclip
if len(sys.argv) > :
# Get address from command line.
address = ' '.join(sys.argv[:])
else:
# Get address from clipboard.
address = pyperclip.paste()
webbrowser.open('https://www.google.com/maps/place/' + address)

2 利用 Requests 模块

requests.get()函数接受一个要下载的 URL 字符串。通过在 requests.get()的返回值上调用 type(),你可以看到它返回一个 Response 对象,其中包含了 Web 服务器对你的请求做出的响应。

 >>>import requests
>>>res = requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')
>>>type(res)
<class 'requests.models.Response'>
>>>res.status_code == requests.codes.ok
True
>>> len(res.text) >>> print(res.text[:])
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever. You may copy it, give it away or
re-use it under the terms of the Proje

Response 对象有一个 status_code 属性,可以检查它是否等于requests.codes.ok,了解下载是否成功。检查成功有一种简单的方法,就是在 Response对象上调用 raise_for_status()方法。如果下载文件出错,这将抛出异常。如果下载成功,就什么也不做。

保存文件:

1.调用 requests.get()下载该文件。
2.用'wb'调用 open(),以写二进制的方式打开一个新文件。
3.利用 Respose 对象的 iter_content()方法做循环。
4.在每次迭代中调用 write(),将内容写入该文件。
5.调用 close()关闭该文件。

3 利用 BeautifulSoup 模块

BeautifulSoup是一个模块,用于从HTML页面中提取信息(用于这个目的时,它比正则表达式好很多)。 BeautifulSoup模块的名称是bs4(表示 BeautifulSoup,第4版)。

创建对象:

利用 requests.get()函数

>>> import requests, bs4
>>> res = requests.get('http://nostarch.com')
>>> res.raise_for_status()
>>> noStarchSoup = bs4.BeautifulSoup(res.text)
>>> type(noStarchSoup)
<class 'bs4.BeautifulSoup'>

传递一个 File 对象

>>> exampleFile = open('example.html')
>>> exampleSoup = bs4.BeautifulSoup(exampleFile)
>>> type(exampleSoup)
<class 'bs4.BeautifulSoup'>

用 select()方法寻找元素

传递给 select()方法的选择器 将匹配…
soup.select('div') 所有名为<div>的元素
soup.select('#author') 带有 id 属性为 author 的元素
soup.select('.notice') 所有使用 CSS class 属性名为 notice 的元素
soup.select('div span') 所有在<div>元素之内的<span>元素
soup.select('div > span') 所有直接在<div>元素之内的<span>元素, 中间没有其他元素
soup.select('input[name]') 所有名为<input>,并有一个 name 属性,其值无所谓的元素
soup.select('input[type="button"]') 所有名为<input>,并有一个 type 属性,其值为 button 的元素

Ex:

#!example.html 
<!-- This is the example.html example file. -->
<html><head><title>The Website Title</title></head>
<body>
<p>Download my <strong>Python</strong> book from <a href="http://
inventwithpython.com">my website</a>.</p>
<p class="slogan">Learn Python the easy way!</p>
<p>By <span id="author">Al Sweigart</span></p>
</body></html>
>>> import bs4
>>> exampleFile = open('example.html')
>>> exampleSoup = bs4.BeautifulSoup(exampleFile.read())
>>> elems = exampleSoup.select('#author')
>>> type(elems)
<class 'list'>
>>> len(elems) >>> type(elems[])
<class 'bs4.element.Tag'>
>>> elems[].getText()
'Al Sweigart'
>>> str(elems[])
'<span id="author">Al Sweigart</span>'
>>> elems[].attrs
{'id': 'author'}

通过元素的属性获取数据

>>> import bs4
>>> soup = bs4.BeautifulSoup(open('example.html'))
>>> spanElem = soup.select('span')[]
>>> str(spanElem)
'<span id="author">Al Sweigart</span>'
>>> spanElem.get('id')
'author'
>>> spanElem.get('some_nonexistent_addr') == None
True
>>> spanElem.attrs
{'id': 'author'}