search
HomeBackend DevelopmentPython TutorialPython uses the lxml module and Requests module to crawl HTML pages

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

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

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

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>

知道这个后,我们可以创建正确的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;)

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

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;]

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

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

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


Statement
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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools