使用 Beautiful Soup 在 Python 中抓取网页
requests
库提取 HTML 内容。requests
库可以从网站获取 HTML 内容。Beautiful Soup 解析 HTML 并将其转换为 Python 对象。在Python 3中需要安装下面两个库:[root@localhost ~]# pip3 install requests beautifulsoup4
https://notes.ayushsharma.in/technology
requests
从这个页面获取 HTML 内容:#!/usr/bin/python3
import requests
url = 'https://notes.ayushsharma.in/technology'
data = requests.get(url)
print(data.text)
data
将包含页面的 HTML 源代码。<div class="col">
<a href="/2021/08/using-variables-in-jekyll-to-define-custom-content" class="post-card">
<div class="card">
<div class="card-body">
<h5 class="card-title">Using variables in Jekyll to define custom content</h5>
<small class="card-text text-muted">I recently discovered that Jekyll's config.yml can be used to define custom
variables for reusing content. I feel like I've been living under a rock all this time. But to err over and
over again is human.</small>
</div>
<div class="card-footer text-end">
<small class="text-muted">Aug 2021</small>
</div>
</div>
</a>
</div>
.card-title
有文章标题, .card-text
有摘录, .card-footer
类下面的small
标签 有发布日期。#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
from pprint import pprint
url = 'https://notes.ayushsharma.in/technology'
data = requests.get(url)
my_data = []
html = BeautifulSoup(data.text, 'html.parser')
articles = html.select('a.post-card')
for article in articles:
title = article.select('.card-title')[0].get_text()
excerpt = article.select('.card-text')[0].get_text()
pub_date = article.select('.card-footer small')[0].get_text()
my_data.append({"title": title, "excerpt": excerpt, "pub_date": pub_date})
pprint(my_data)
END
官方站点:www.linuxprobe.com
Linux命令大全:www.linuxcool.com
刘遄老师QQ:5604241
Linux技术交流群:3762708
(新群,火热加群中……)
想要学习Linux系统的读者可以点击"阅读原文"按钮来了解书籍《Linux就该这么学》,同时也非常适合专业的运维人员阅读,成为辅助您工作的高价值工具书!
微信扫码关注该文公众号作者
戳这里提交新闻线索和高质量文章给我们。
来源: qq
点击查看作者最近其他文章