️ 什么是爬虫?
定义:
网络爬虫(Web Crawler)是一种自动访问网页并提取数据的程序。
常见用途:
️ 使用 requests 库发起网络请求
pip install requests
基本用法:
import requests
url = "https://example.com"
response = requests.get(url)
print("状态码:", response.status_code)
print("网页内容:", response.text[:500]) # 预览前500字符
常用参数:
requests.get(url, params={'key': 'value'}, headers={'User-Agent': '...'})
# 示例:
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get("https://httpbin.org/get", headers=headers)
初识 HTML 结构
网站返回的文本通常是 HTML,结构如下:
<html>
<head>
<title>标题title>
head>
<body>
<h1>主标题h1>
<p class="info">这是段落p>
body>
html>
我们后续会用工具(如 BeautifulSoup)提取这些标签中的内容。
使用 requests 获取以下网址内容:
打印网页的状态码、响应头和部分内容。
额外挑战:试着获取你感兴趣的网站首页源码,比如:
# url = "https://movie.douban.com/"
# url = "https://www.jianshu.com"
# url = "https://www.zhihu.com"
url = "https://www.bilibili.com"
headers = {
'Accept': 'application/json, text/plain, */*',
'Host': 'www.bilibili.com',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0'
}
response = requests.get(url, headers=headers)
print("状态码:", response.status_code)
print("网页内容:", response.text)