用python爬取百度网页链接后爬取链接内容
时间: 2024-12-14 15:26:25 浏览: 19
在Python中,我们可以使用requests库来发送HTTP请求获取网页内容,然后利用BeautifulSoup库解析HTML文档并提取链接。以下是简单的步骤:
1. 安装所需库:
```
pip install requests
pip install beautifulsoup4
```
2. 编写爬虫代码:
```python
import requests
from bs4 import BeautifulSoup
# 目标URL
url = "https://www.baidu.com"
# 发送GET请求获取网页内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 找到所有a标签(包含链接)
links = soup.find_all('a')
# 提取每个链接的href属性
for link in links:
href = link.get('href')
# 如果href是实际的URL(非相对路径等)
if href.startswith('http'):
print(f"发现链接:{href}")
# 如果需要进一步爬取链接内容,可以对提取的链接递归地重复以上过程
else:
print("请求失败")
```
这个脚本首先会打印出目标页面上所有的外部链接。如果你想要继续抓取这些链接的内容,只需将上述循环中的`print`替换为一个新的网络请求,并进行相应的处理。
阅读全文
相关推荐


















