网络爬虫是一个可以自动抓取互联网内容的程序。Python有很多库可以用来实现网络爬虫,其中最常用的是requests
(用于发送HTTP请求)和BeautifulSoup
(用于解析HTML)。
以下是一个简单的Python网络爬虫示例,该爬虫会抓取指定网页的所有标题(<title>
标签)并打印出来:
import requests
from bs4 import BeautifulSoup
def get_titles(url):
# 发送HTTP请求
response = requests.get(url)
# 检查请求是否成功
if response.status_code != 200:
print(f"Failed to retrieve the webpage. Status code: {response.status_code}")
return []
# 解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 查找所有的<title>标签
titles = soup.find_all('title')
# 提取并返回标题文本
return [title.text for title in titles]
# 使用示例
url = 'https://www.exam.....pl....e.com' # 替换为你想要爬取的网页URL
titles = get_titles(url)
for title in titles:
print(title)