Home Backend Development Python Tutorial Python uses the lxml module and Requests module to crawl HTML pages

Python uses the lxml module and Requests module to crawl HTML pages

Mar 02, 2017 pm 04:37 PM

Web抓取

Web站点使用HTML描述,这意味着每个web页面是一个结构化的文档。有时从中 获取数据同时保持它的结构是有用的。web站点不总是以容易处理的格式, 如 csv 或者 json 提供它们的数据。

这正是web抓取出场的时机。Web抓取是使用计算机程序将web页面数据进行收集 并整理成所需格式,同时保存其结构的实践。

lxml和Requests
lxml(http://lxml.de/)是一个优美的扩展库,用来快速解析XML以及HTML文档 即使所处理的标签非常混乱。我们也将使用 Requests (http://docs.python-requests.org/en/latest/#)模块取代内建的urllib2模块,因为其速度更快而且可读性更好。你可以通过使用 pip install lxml 与 pip install requests 命令来安装这两个模块。

让我们以下面的导入开始:

from lxml import html
import requests
Copy after login

下一步我们将使用 requests.get 来从web页面中取得我们的数据, 通过使用 html 模块解析它,并将结果保存到 tree 中。

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.text)
Copy after login

tree 现在包含了整个HTML文件到一个优雅的树结构中,我们可以使用两种 方法访问:XPath以及CSS选择器。在这个例子中,我们将选择前者。

XPath是一种在结构化文档(如HTML或XML)中定位信息的方式。一个关于XPath的 不错的介绍参见 W3Schools 。

有很多工具可以获取元素的XPath,如Firefox的FireBug或者Chrome的Inspector。 如果你使用Chrome,你可以右键元素,选择 ‘Inspect element',高亮这段代码, 再次右击,并选择 ‘Copy XPath'。

在进行一次快速分析后,我们看到在页面中的数据保存在两个元素中,一个是title是 ‘buyer-name' 的p,另一个class是 ‘item-price' 的span:

<p title="buyer-name">Carson Busses</p>
<span class="item-price">$29.95</span>
Copy after login

知道这个后,我们可以创建正确的XPath查询并且使用lxml的 xpath 函数, 像下面这样:

#这将创建buyers的列表:
buyers = tree.xpath(&#39;//p[@title="buyer-name"]/text()&#39;)
#这将创建prices的列表:
prices = tree.xpath(&#39;//span[@class="item-price"]/text()&#39;)
Copy after login

让我们看看我们得到了什么:

print &#39;Buyers: &#39;, buyers
print &#39;Prices: &#39;, prices
Buyers: [&#39;Carson Busses&#39;, &#39;Earl E. Byrd&#39;, &#39;Patty Cakes&#39;,
&#39;Derri Anne Connecticut&#39;, &#39;Moe Dess&#39;, &#39;Leda Doggslife&#39;, &#39;Dan Druff&#39;,
&#39;Al Fresco&#39;, &#39;Ido Hoe&#39;, &#39;Howie Kisses&#39;, &#39;Len Lease&#39;, &#39;Phil Meup&#39;,
&#39;Ira Pent&#39;, &#39;Ben D. Rules&#39;, &#39;Ave Sectomy&#39;, &#39;Gary Shattire&#39;,
&#39;Bobbi Soks&#39;, &#39;Sheila Takya&#39;, &#39;Rose Tattoo&#39;, &#39;Moe Tell&#39;]

Prices: [&#39;$29.95&#39;, &#39;$8.37&#39;, &#39;$15.26&#39;, &#39;$19.25&#39;, &#39;$19.25&#39;,
&#39;$13.99&#39;, &#39;$31.57&#39;, &#39;$8.49&#39;, &#39;$14.47&#39;, &#39;$15.86&#39;, &#39;$11.11&#39;,
&#39;$15.98&#39;, &#39;$16.27&#39;, &#39;$7.50&#39;, &#39;$50.85&#39;, &#39;$14.26&#39;, &#39;$5.68&#39;,
&#39;$15.00&#39;, &#39;$114.07&#39;, &#39;$10.09&#39;]
Copy after login

恭喜!我们已经成功地通过lxml与Request,从一个web页面中抓取了所有我们想要的 数据。我们将它们以列表的形式存在内存中。现在我们可以对它做各种很酷的事情了: 我们可以使用Python分析它,或者我们可以将之保存为一个文件并向世界分享。

我们可以考虑一些更酷的想法:修改这个脚本来遍历该例数据集中剩余的页面,或者 使用多线程重写这个应用从而提升它的速度。

更多Python使用lxml模块和Requests模块抓取HTML页面相关文章请关注PHP中文网!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles