【发布时间】: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>©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