python爬虫完整代码实例
- python
- 2024-05-15 18:32:46
- 376
使用
标签
| 代码块 | 描述 |
|---|---|
| python
import requests
from bs4 import BeautifulSoup
发起请求
response = requests.get(url)
解析 HTML
soup = BeautifulSoup(response.text, '
.parser')
提取数据
| 请求和解析 HTML |
| python
for article in soup.find_all('article'):
title = article.find('h2').text
content = article.find('p').text
print(title, content)
| 提取数据 |
使用 标签
- import requests:导入 requests 库,用于发送 HTTP 请求。
- from bs4 import BeautifulSoup:导入 BeautifulSoup,用于解析 HTML。
- response = requests.get(url):使用 requests 发起一个 GET 请求,其中 url 是目标网站的 URL。
- soup = BeautifulSoup(response.text, '
.parser'):使用 BeautifulSoup 解析 HTML 响应,指定解析器为 HTML 解析器。
- for article in soup.find_all('article'):使用 find_all() 方法查找 HTML 中所有匹配指定标识符(article)的标签。
- title = article.find('h2').text:查找每个 article 标签内的 h2 标签,并提取其文本内容(标题)。
- content = article.find('p').text:查找每个 article 标签内的第一个 p 标签,并提取其文本内容(文章内容)。
- print(title, content):使用 print() 打印标题和文章内容。