Python 爬虫快速入门
本文详细介绍了 Python 爬虫的基础知识与实战技巧。涵盖 urllib 库的使用,包括请求发送、响应读取、编码转换及文件写入。深入讲解了 GET 与 POST 请求的处理方法,并通过百度翻译、肯德基门店查询、百度贴吧及豆瓣电影等实际案例演示了如何定位 URL、封装 Headers、处理 JSON 数据以及解析 Ajax 接口。此外,文章补充了异常处理机制、Robots 协议遵循及反爬策略建议,帮助开发者构建稳定且合规的爬虫程序。

本文详细介绍了 Python 爬虫的基础知识与实战技巧。涵盖 urllib 库的使用,包括请求发送、响应读取、编码转换及文件写入。深入讲解了 GET 与 POST 请求的处理方法,并通过百度翻译、肯德基门店查询、百度贴吧及豆瓣电影等实际案例演示了如何定位 URL、封装 Headers、处理 JSON 数据以及解析 Ajax 接口。此外,文章补充了异常处理机制、Robots 协议遵循及反爬策略建议,帮助开发者构建稳定且合规的爬虫程序。

引入模块
from urllib import request
定义 URL 路径
url = "http://www.baidu.com"
发送请求
使用 urlopen 发送请求,返回一个响应对象 response。
response = request.urlopen(url)
读取响应体 以字节形式获取网页源码。
raw_data = response.read()
编码转换 网络传输通常为字节流,需解码为文本。
encode)decode)# 将字节转为 UTF-8 文本
text = response.read().decode("utf-8")
print(text)
写入文件 将爬取内容保存至本地。
with open('example.html', 'w', encoding='utf-8') as fp:
fp.write(text)
常用属性与方法
response.getcode()response.geturl()response.getheaders()在构建请求前,确保参数编码格式正确。
引入模块
from urllib import parse
单个参数编码/解码
# 编码
result = parse.quote("小鲁班")
# 解码
result1 = parse.unquote("%E9%E1%3E")
多个参数编码方式 1 (format)
url2 = "http://www.baidu.com?name={}&pwd={}"
url1 = url2.format(parse.quote('用户名'), parse.quote('密码'))
多个参数编码方式 2 (urlencode)
obj = {
"name": "肖",
"password": "213123 丽华",
"age": "五十岁"
}
base_url = "http://www.baidu.com/s?"
params = parse.urlencode(obj)
url = base_url + params
用于直接下载资源文件。
request.urlretrieve('图片路径', '保存路径')
服务器通常通过 User-Agent 识别爬虫。封装请求对象可携带 Cookie、UA 等信息。
url = "http://www.baidu.com/"
headers = {
'User-Agent': "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.91 Mobile Safari/537.36"
}
req = request.Request(url=url, headers=headers)
response = request.urlopen(req)
post_url = "https://fanyi.baidu.com/sug"
data_dict = {"kw": "sogreat"}
data = parse.urlencode(data_dict)
data = data.encode("utf-8")
rq = request.Request(url=post_url, headers={}, data=data)
response = request.urlopen(rq)
text = response.read().decode('utf-8')
import json
json_obj = json.loads(text, encoding='utf-8')
for s in json_obj["data"]:
print(s)
import json
from urllib import request, parse
headers1 = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 Edg/100.0.1185.44"
}
newaddr = input("请输入地址:")
KFCurl = "http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword"
pageindex = 1
def prepare_url(url, headers, datas):
params = parse.urlencode(datas)
data = params.encode(encoding="utf-8")
req = request.Request(url=url, headers=headers, data=data)
return req
def request_with_url(reqs):
response1 = request.urlopen(reqs)
address = response1.read().decode('utf-8')
return address
def parse_data(text):
try:
address1 = json.loads(text)
if len(address1['Table1']) == 0:
return 'null'
for addr in address1['Table1']:
print(addr)
except Exception as e:
print(f"解析错误:{e}")
return 'error'
while True:
datas = {
"cname": "",
"pid": "",
"pageIndex": pageindex,
"pageSize": 10,
"keyword": newaddr
}
reqs = prepare_url(KFCurl, headers1, datas)
text = request_with_url(reqs)
if parse_data(text) == "null":
break
pageindex += 1
import urllib.request
headers1 = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 Edg/100.0.1185.44"
}
input_name = "%E6%96%97%E7%BD%97%E5%A4%A7%E9%99%86" # 斗罗大陆
start_page = 1
end_page = 5
for page in range(start_page, end_page + 1):
url = "https://tieba.baidu.com/f?kw{}=&ie=utf-8&pn={}".format(input_name, (page - 1) * 50)
request_obj = urllib.request.Request(url=url, headers=headers1)
response = urllib.request.urlopen(request_obj)
text = response.read().decode('utf-8')
file_path = "page{}.html".format(page)
with open(file_path, 'w', encoding="utf-8") as fp:
fp.write(text)
print(file_path, "下载完毕")
print("所有内容下载完毕")
import json
from urllib import request
headers = {
'User-Agent': "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.91 Mobile Safari/537.36"
}
base_url = "https://movie.douban.com/j/new_search_subjects?sort=U&range=0,10&tags=&start={}&genres=%E5%8A%A8%E7%94%BB"
for p in range(0, 4):
total = p * 20
url = base_url.format(total)
req = request.Request(url=url, headers=headers)
response = request.urlopen(req)
text = response.read().decode('utf-8')
json_obj = json.loads(text)
for val in json_obj['data']:
title = val['title']
rate = val['rate']
print("title:{},rate:{}".format(title, rate))
在实际爬虫开发中,网络波动和目标网站策略变化是常态,完善的异常处理至关重要。
使用 try-except 块包裹网络请求代码,防止程序因单次请求失败而中断。
try:
response = request.urlopen(req, timeout=10)
except Exception as e:
print(f"请求失败:{e}")
在爬取任何网站前,应检查其 robots.txt 协议,尊重网站的爬取规则,避免对目标服务器造成过大压力。
连续高频请求可能被判定为攻击。建议在循环中加入随机延时。
import time
import random
time.sleep(random.uniform(1, 3))
爬虫技术应用于合法合规的数据采集,严禁爬取个人隐私数据、商业机密或违反相关法律法规的内容。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online