Python爬虫学习笔记
  • Introduction
  • 爬虫简介
    • 1.1 了解网页结构
  • BeautifulSoup 解析网页
    • 2.1 BeautifulSoup 解析网页: 基础
    • 2.2 BeautifulSoup 解析网页: CSS
    • 2.3 BeautifulSoup 解析网页: 正则表达
    • 2.4 小练习: 爬百度百科
  • 更多请求/下载方式
    • 3.1 多功能的 Requests
    • 3.2 下载文件
    • 3.3 小练习: 下载美图
  • 加速你的爬虫
    • 4.1 加速爬虫: 多进程分布式
    • 4.2 加速爬虫: 异步加载 Asyncio
  • 高级爬虫
    • 5.1 高级爬虫: 让 Selenium 控制你的浏览器帮你爬
    • 5.2 高级爬虫: 高效无忧的 Scrapy 爬虫库
Powered by GitBook
On this page
  • 网页基本组成部分
  • 用 Python 登录网页
  • 匹配网页内容

Was this helpful?

  1. 爬虫简介

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']
Previous爬虫简介NextBeautifulSoup 解析网页

Last updated 6 years ago

Was this helpful?