仅使用内置库使用 Python 制作基本的网络抓取工具 - Python

2023-11-25

学习Python,我试图制作一个没有任何第三方库的网络爬虫,这样这个过程对我来说就不会被简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些资源都让我对某些事情感到困惑。

html 看起来像这样,

<html>
<head>...</head>
<body>
    *lots of other <div> tags*
<div class = "want" style="font-family:verdana;font-size:12px;letter-spacing:normal"">
<form class ="subform">...</form>
<div class = "subdiv1" >...</div>
<div class = "subdiv2" >...</div>
    *lots of other <div> tags*
</body>
</html>

我想要刮刀提取<div class = "want"...>*content*</div>并将其保存到 html 文件中。

我对如何解决这个问题有一个非常基本的想法。

import urllib
from urllib import request
#import re
#from html.parser import HTMLParser

response = urllib.request.urlopen("http://website.com")
html = response.read()

#Some how extract that wanted data

f = open('page.html', 'w')
f.write(data)
f.close()

标准库附带了各种结构化标记处理工具,您可以使用它来解析 HTML,然后搜索它以提取您的 div。

那里有很多选择。你用什么?

html.parser看起来是显而易见的选择,但我实际上会从ElementTree反而。它是一个非常好的、非常强大的 API,网络上有大量的文档和示例代码可以帮助您入门,并且有很多专家每天使用它来帮助您解决问题。如果事实证明 etree 无法解析您的 HTML,您将不得不使用其他东西......但首先尝试一下。

例如,通过对 HTML 片段进行一些小修复,使其实际上有效,因此实际上有一些文本值得从您的 div 中删除:

<html>
<head>...</head>
<body>
    *lots of other <div /> tags*
<div class = "want" style="font-family:verdana;font-size:12px;letter-spacing:normal">spam spam spam
<form class ="subform">...</form>
<div class = "subdiv1" >...</div>
<div class = "subdiv2" >...</div>
    *lots of other <div /> tags*
</div>
</body>
</html>

您可以使用这样的代码(我假设您知道或愿意学习 XPath):

tree = ElementTree.fromstring(page)
mydiv = tree.find('.//div[@class="want"]')

现在您已经获得了对div与类"want"。您可以通过以下方式获取其直接文本:

print(mydiv.text)

但如果你想提取整个子树,那就更容易了:

data = ElementTree.tostring(mydiv)

如果你想把它包装在一个有效的<html> and <body>和/或删除<div>本身,您必须手动完成该部分。该文档解释了如何使用简单的树 API 构建元素:您创建一个head and a body放入html,然后粘上div in the body, then tostring the html,就是这样。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅使用内置库使用 Python 制作基本的网络抓取工具 - Python 的相关文章

随机推荐