分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

从Web抓取信息

发布时间:2023-09-06 02:36责任编辑:顾先生关键词: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()函数打开外部浏览器

1 import webbrowser, sys, pyperclip2 if len(sys.argv) > 1:3 ????# Get address from command line.4 ????address = ‘ ‘.join(sys.argv[1:])5 else:6 ????# Get address from clipboard.7 ????address = pyperclip.paste()8 webbrowser.open(‘https://www.google.com/maps/place/‘ + address)

2 利用 Requests 模块

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

 1 >>>import requests 2 >>>res = requests.get(‘http://www.gutenberg.org/cache/epub/1112/pg1112.txt‘) 3 >>>type(res) 4 <class ‘requests.models.Response‘> 5 >>>res.status_code == requests.codes.ok 6 True 7 >>> len(res.text) 8 178981 9 >>> print(res.text[:250])10 The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare11 12 This eBook is for the use of anyone anywhere at no cost and with13 almost no restrictions whatsoever. You may copy it, give it away or14 re-use it under the terms of the Proje

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

未完待续

 

从Web抓取信息

原文地址:https://www.cnblogs.com/hjzhoublog/p/10614333.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved