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

Was this helpful?

  1. BeautifulSoup 解析网页

2.1 BeautifulSoup 解析网页: 基础

要输出< h1>标题, 可以就直接soup.h1:

soup = BeautifulSoup(html, features='lxml')
print(soup.h1)

"""
<h1>爬虫测试1</h1>
"""

print('\n', soup.p)

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

如果网页中有多个同样的 tag, 比如链接< a>, 可以使用find_all来找到所有的选项. 因为真正的 link 不是在< a>中间< /a>,而是在< a href = 'link'>里面, 也可以看做是< a>的一个属性.用像 Python 字典的形式, 用 key 来读取l['href']

"""
<a href="https://morvanzhou.github.io/tutorials/scraping">爬虫教程</a>
"""

all_href = soup.find_all('a')
all_href = [l['href'] for l in all_href]
print('\n', all_href)

# ['https://morvanzhou.github.io/', 'https://morvanzhou.github.io/tutorials/scraping']
PreviousBeautifulSoup 解析网页Next2.2 BeautifulSoup 解析网页: CSS

Last updated 6 years ago

Was this helpful?