python网页爬虫代码
pythonimport requests
from bs4 import BeautifulSoup
# 定义要爬取的网页链接
url = 'http://example.com'
# 发送HTTP请求获取页面内容
response = requests.get(url)
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取页面标题
title = soup.title.text
print('网页标题:', title)
# 获取所有链接
links = soup.find_all('a')
print('所有链接:')
for link in links:
print(link.get('href'))
确保你已经安装了 requests 和 beautifulsoup4 包,你可以通过
pip install requests beautifulsoup4
pythonimport requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def crawl(url, depth=1, max_depth=5):
# 检查深度是否超过最大深度
if depth > max_depth:
return
try:
# 发送HTTP请求获取页面内容
response = requests.get(url)
response.raise_for_status() # 检查是否有错误发生
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取页面标题
title = soup.title.text
print('标题:', title)
# 获取所有链接
links = soup.find_all('a')
print('链接:')
for link in links:
href = link.get('href')
# 绝对化链接
absolute_url = urljoin(url, href)
print(absolute_url)
# 递归调用crawl函数,爬取链接的内容
crawl(absolute_url, depth + 1, max_depth)
except Exception as e:
print("爬取失败:", e)
# 定义要爬取的网页链接
starting_url = 'http://example.com'
# 设置最大深度
max_depth = 2
# 调用crawl函数开始爬取
crawl(starting_url, max_depth=max_depth)
这个改进后的版本包含了对异常的处理,限制了爬取深度,并且使用了 urljoin 函数来绝对化链接,确保链接是完整的。你可以根据需要修改最大深度或其他参数。