1.1 了解网页结构

网页基本组成部分

在 HTML 中, 基本上所有的实体内容, 都会有个 tag 来框住它. 而这个被tag 住的内容, 就可以被展示成不同的形式, 或有不同的功能

主体的 tag 分成两部分,header和body

在header中, 存放这一些网页的网页的元信息, 比如说title

这些信息是不会被显示到你看到的网页中的. 这些信息大多数时候是给浏览器看, 或者是给搜索引擎的爬虫看

<head>
    <meta charset="UTF-8">
    <title>Scraping tutorial 1 | 莫烦Python</title>
    <link rel="icon" href="https://morvanzhou.github.io/static/img/description/tab_icon.png">
</head>

HTML 的第二大块是body, 这个部分才是你看到的网页信息. 网页中的heading, 视频, 图片和文字等都存放在这里.

﹤h1﹥﹤/h1﹥tag 就是主标题, 呈现出来的效果就是大一号的文字.

﹤p﹥﹤/p﹥ 里面的文字就是一个段落.

﹤a﹥﹤/a﹥里面都是一些链接.

<body>
    <h1>爬虫测试1</h1>
    <p>
        这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
        <a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.
    </p>
</body>

用 Python 登录网页

因为网页中存在中文, 为了正常显示中文, read() 完以后, 要对读出来的文字进行转换, decode() 成可以正常显示中文的形式

>>>from urllib.request import urlopen

>>># if has Chinese, apply decode()
>>>html = urlopen(
    "https://morvanzhou.github.io/static/scraping/basic-structure.html"
).read().decode('utf-8')
>>>print(html)

>>><!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <title>Scraping tutorial 1 | 莫烦Python</title>
    <link rel="icon" href="https://morvanzhou.github.io/static/img/description/tab_icon.png">
</head>
<body>
    <h1>爬虫测试1</h1>
    <p>
        这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
        <a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.
    </p>

</body>
</html>

匹配网页内容

选好要使用的 tag 名称 < title>,找到这个网页的 title

import re
res = re.findall(r"<title>(.+?)</title>", html)
print("\nPage title is: ", res[0])

# Page title is:  Scraping tutorial 1 | 莫烦Python

想要找到中间的段落 < p>, 因为这个段落在 HTML 中还夹杂着 tab,new line, 所以给一个 flags=re.DOTALL 来对这些 tab, new line不敏感

res = re.findall(r"<p>(.*?)</p>", html, flags=re.DOTALL)    # re.DOTALL if multi line
print("\nPage paragraph is: ", res[0])

# Page paragraph is:
#  这是一个在 <a href="https://morvanzhou.github.io/">莫烦Python</a>
#  <a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a> 中的简单测试.

找所有的链接

res = re.findall(r'href="(.*?)"', html)
print("\nAll links: ", res)
# All links:
['https://morvanzhou.github.io/static/img/description/tab_icon.png',
'https://morvanzhou.github.io/',
'https://morvanzhou.github.io/tutorials/scraping']

Last updated