Requests - 使用请求进行 Web 抓取
我们已经了解了如何使用 Python 请求库从给定 URL 获取数据。我们将尝试从 Tutorialspoint 网站抓取数据,该网站位于 https://www.tutorialspoint.com/tutorialslibrary.htm,使用以下 −
- 请求库
- 来自 Python 的 Beautiful soup 库
我们已经安装了请求库,现在让我们安装 Beautiful soup 包。如果您想了解 beautiful soup 的更多功能,请访问以下网址:https://www.crummy.com/software/BeautifulSoup/bs4/doc/。
安装 Beautifulsoup
我们将在下面看到如何安装 Beautiful Soup−
E:\prequests>pip install beautifulsoup4 Collecting beautifulsoup4 Downloading https://files.pythonhosted.org/packages/3b/c8/a55eb6ea11cd7e5ac4ba cdf92bac4693b90d3ba79268be16527555e186f0/beautifulsoup4-4.8.1-py3-none-any.whl ( 101kB) |████████████████████████████████| 102kB 22kB/s Collecting soupsieve>=1.2 (from beautifulsoup4) Downloading https://files.pythonhosted.org/packages/81/94/03c0f04471fc245d08d0 a99f7946ac228ca98da4fa75796c507f61e688c2/soupsieve-1.9.5-py2.py3-none-any.whl Installing collected packages: soupsieve, beautifulsoup4 Successfully installed beautifulsoup4-4.8.1 soupsieve-1.9.5
现在我们已安装好 Python 请求库和 Beautiful Soup。
现在让我们编写代码,从给定的 URL 中抓取数据。
网页抓取
import requests from bs4 import BeautifulSoup res = requests.get('https://www.tutorialspoint.com/tutorialslibrary.htm') print("The status code is ", res.status_code) print(" ") soup_data = BeautifulSoup(res.text, 'html.parser') print(soup_data.title) print(" ") print(soup_data.find_all('h4'))
使用请求库,我们可以从给定的 URL 获取内容,而 beautiful soup 库可以帮助解析它并按照我们想要的方式获取详细信息。
您可以使用 beautiful soup 库通过 Html 标签、类、id、css 选择器等多种方式获取数据。以下是我们得到的输出,其中我们打印了页面的标题以及页面上的所有 h4 标签。
输出
E:\prequests>python makeRequest.py The status code is 200 <title>Free Online Tutorials and Courses</title> [<h4>Academic</h4>, <h4>Computer Science</h4>, <h4>Digital Marketing</h4>, <h4>Monuments</h4>,<h4>Machine Learning</h4>, <h4>Mathematics</h4>, <h4>Mobile Development</h4>,<h4>SAP</h4>, <h4>Software Quality</h4>, <h4>Big Data & Analytics</h4>, <h4>Databases</h4>, <h4>Engineering Tutorials</h4>, <h4>Mainframe Development</h4>, <h4>Microsoft Technologies</h4>, <h4>Java Technologies</h4>, <h4>XML Technologies</h4>, <h4>Python Technologies</h4>, <h4>Sports</h4>, <h4>Computer Programming</h4>,<h4>DevOps</h4>, <h4>Latest Technologies</h4>, <h4>Telecom</h4>, <h4>Exams Syllabus</h4>, <h4>UPSC IAS Exams</h4>, <h4>Web Development</h4>, <h4>Scripts</h4>, <h4>Management</h4>,<h4>Soft Skills</h4>, <h4>Selected Reading</h4>, <h4>Misc</h4>]