【问题标题】:questions of a simple web crawler一个简单的网络爬虫的问题
【发布时间】:2018-01-18 17:20:56
【问题描述】:

我最近在用python学习网络爬虫,有一些问题在一个小示例代码中。它有一个本地 html 文件,其中包含一些图像和一个抓取它的 .py 文件。

html文件'first_web.html':

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>First web</title>
    <link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
    <div class="header">
        <h1>First web</h1>
    </div>
    <div class="main-content">
        <ul class="article">
            <li>
                <img src="1.jpg" width="100" height="90">
                <h3>first</h3>
                <p>This is first</p>
            </li>
            <li>
                <img src="2.jpg" width="100" height="90">
                <h3>second</h3>
                <p>This is second</p>
            </li>
            <li>
                <img src="3.jpg" width="100" height="90">
                <h3>Third</h3>
                <p>This is Third</p>
            </li>
        </ul>
    </div>
    <div class="footer">
        <p>&copy;Alex</p>
    </div>
</body>
</html>

这是 .py 文件:

from lxml import etree
f = open('first_web.html','r',encoding='utf-8')
# print(f.read())
html = etree.HTML(f.read())
for i in range(1,4):
    img = html.xpath('//div[2]/ul/li[{}]/img/@src'.format(i))[0]
    print(img)

想问一下这行代码中的li[{}]、.format[i]、@src和[0]是什么意思?

img = html.xpath('//div[2]/ul/li[{}]/img/@src'.format(i))[0]

【问题讨论】:

    标签: python html css xpath web-crawler


    【解决方案1】:

    {} 是一个占位符,由于.format() 调用而成为i 的值。

    >>> print 'My name is {}'.format('Steve')
    My name is Steve
    

    [0] 表示“此列表中的第一项”,即html.xpath(...) 返回多个值,我们只想要第一个。

    >>> mylist = [ 'Apples', 'Oranges', 'Bananas' ]
    >>> print mylist[0]
    Apples
    

    【讨论】:

    • 感谢它有很大帮助!请问@src 是干什么用的?
    • @src 是请求img 标记的src 属性的xpath 方式。
    【解决方案2】:

    这一行利用 python 的str.format 功能创建了一个xpath expression

    这里将 python 字符串格式与 xpath 表达式分开有点棘手。

    li[{}] 是 xpath 的一部分,{} 是您要查询的 li 元素的索引。由于您对此有一个循环,并希望将 python 变量 i 的值包含在表达式中。 {} 将被替换为具有i 值的格式。

    @src 是 xpath 的一部分,它告诉我:“请给我所选 img-tag 中 src-attribute 的值”。

    最后的[0] 在那里,因为xpath 总是返回一个列表并且您想要第一个元素。事实上,您的表达式确保只有一个结果。

    如果您希望它适用于任意数量的图像,您可能会完全放弃范围循环和格式化部分并直接使用 xpath:

    for img in html.xpath('//div[2]/ul/li/img/@src'):
        print(img)
    

    这样你就可以在 HTML 中查询第二个 div 容器列表中的所有 img 标签并获取它们的 src 属性。

    【讨论】:

      猜你喜欢
      • 2015-06-26
      • 2023-03-13
      • 1970-01-01
      • 2017-01-26
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      相关资源
      最近更新 更多