python爬虫-bs4案例
时间: 2023-10-04 11:05:47 浏览: 148
当然,我可以给你提供一个简单的 Python 爬虫案例,使用 Beautiful Soup 4 (bs4) 库进行网页解析。以下是一个示例,用于爬取一个网页上的文章标题和链接:
```python
import requests
from bs4 import BeautifulSoup
# 发送 HTTP 请求获取网页内容
url = "http://example.com" # 替换为你要爬取的网页链接
response = requests.get(url)
html_content = response.text
# 使用 Beautiful Soup 解析网页
soup = BeautifulSoup(html_content, "html.parser")
# 查找文章标题和链接
articles = soup.find_all("a", class_="article-link") # 替换为你要提取的标签和类名
for article in articles:
title = article.text
link = article["href"]
print("标题:", title)
print("链接:", link)
print()
```
这个示例中,我们首先使用 `requests` 库发送 HTTP 请求获取网页的 HTML 内容。然后,我们使用 Beautiful Soup 对 HTML 进行解析,并通过 `find_all` 方法查找所有符合条件的标签。最后,我们遍历找到的标签,提取标题和链接并进行打印。
请注意,这只是一个简单的示例,实际的爬虫可能需要更复杂的处理逻辑和异常处理。同时,务必遵守网站的爬取规则和法律法规,确保合法合规地进行网络爬虫操作。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)