HTML 基本语法规则
1. HTML 文档结构
HTML文档由一系列的标签(tags)组成,标签通常成对出现,例如<tagname>内容</tagname>
。标签用来定义文档的结构和内容的含义。
-
<!DOCTYPE html>
:声明文档类型,告诉浏览器这是一个HTML5文档。 -
<html>
:根元素,包裹整个HTML文档。 -
<head>
:包含文档的元数据,如标题(<title>
)、字符集声明(<meta charset="UTF-8">
)等。 -
<body>
:包含文档的可见内容,如文本、图片、链接等。
2. HTML 标签
HTML标签分为块级标签和行内标签。
-
块级标签:独占一行,如
<div>
、<p>
、<h1>
到<h6>
等。 -
行内标签:不会独占一行,如
<span>
、<a>
、<img>
等。
3. HTML 属性
标签可以有属性,属性用来提供额外的信息。
-
id
:唯一标识文档中的一个元素。 -
class
:为元素定义一个类名,用于CSS样式或JavaScript操作。 -
href
:在<a>
标签中指定链接的URL。 -
src
:在<img>
或<script>
标签中指定资源的URL。 -
alt
:在<img>
标签中提供图片的替代文本,用于图片无法显示时。
4. HTML 元素
以下是Python爬虫中可能会用到的一些HTML元素:
-
<a>
:超链接,用于链接到其他页面或资源。<a href="https://www.example.com">Link Text</a>
-
<img>
:图片,用于嵌入图片。<img src="image.jpg" alt="Description">
-
<table>
:表格,用于显示结构化数据。<table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Row 1, Cell 1</td> <td>Row 1, Cell 2</td> </tr> </table>
-
<form>
:表单,用于收集用户输入。<form action="/submit" method="post"> <input type="text" name="username"> <input type="password" name="password"> <button type="submit">Submit</button> </form>
-
<div>
和<span>
:通用容器,用于布局和样式化。
5. HTML 注释
HTML注释用<!--
和-->
包裹,不会显示在浏览器中。
<!-- 这是一个注释 -->
Python 爬虫中常用的HTML元素
1. 超链接(<a>
)
超链接用于链接到其他页面或资源。在爬虫中,可以通过提取<a>
标签的href
属性来获取链接。
<a href="https://www.example.com">Link Text</a>
2. 图片(<img>
)
图片标签用于嵌入图片。在爬虫中,可以通过提取<img>
标签的src
属性来获取图片的URL。
<img src="image.jpg" alt="Description">
3. 表格(<table>
)
表格用于显示结构化数据。在爬虫中,可以通过解析<table>
标签来提取表格数据。
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
</table>
4. 列表(<ul>
、<ol>
、<li>
)
列表用于显示有序或无序的项目列表。在爬虫中,可以通过解析<ul>
或<ol>
标签来提取列表项。
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
5. 表单(<form>
)
表单用于收集用户输入。在爬虫中,可以通过解析<form>
标签来提取表单数据。
<form action="/submit" method="post">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Submit</button>
</form>