文章目录1.1 urllib - Python内置请求库基础使用添加请求头带参数的GET请求POST请求异常处理1.2 requests - 爬虫开发的首选库安装基础请求请求参数的几种传递方式请求头设置Cookie处理代理配置超时和重试响应数据处理1.3 实战综合运用GET/POST请求1.1 urllib - Python内置请求库基础使用urllib不需要安装直接导入使用。虽然不如requests简洁但了解它能帮助你理解HTTP请求的底层逻辑。fromurllib.requestimporturlopen,Requestfromurllib.parseimporturlencode,quotefromurllib.errorimportURLError,HTTPError# 最简单的GET请求withurlopen(https://www.python.org)asresponse:htmlresponse.read().decode(utf-8)print(html[:500])# 打印前500个字符添加请求头不加请求头的请求很容易被识别为爬虫。urlhttps://example.comheaders{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36}# 使用Request对象添加请求头reqRequest(url,headersheaders)withurlopen(req,timeout10)asresponse:htmlresponse.read().decode(utf-8)带参数的GET请求base_urlhttps://example.com/searchparams{keyword:Python爬虫,page:1,size:20}# urlencode将字典转为查询字符串query_stringurlencode(params)full_urlf{base_url}?{query_string}print(full_url)# https://example.com/search?keywordPython%E7%88%AC%E8%99%ABpage1size20POST请求urlhttps://example.com/logindata{username:test,password:123456}# POST数据需要编码为bytespost_dataurlencode(data).encode(utf-8)reqRequest(url,datapost_data,headersheaders)withurlopen(req)asresponse:resultresponse.read().decode(utf-8)print(result)异常处理try:responseurlopen(https://example.com,timeout5)exceptHTTPErrorase:print(fHTTP错误:{e.code}-{e.reason})exceptURLErrorase:print(fURL错误:{e.reason})exceptExceptionase:print(f其他错误:{e})1.2 requests - 爬虫开发的首选库安装pipinstallrequests基础请求requests的API设计非常直观大大简化了HTTP请求的代码量。importrequests# GET请求responserequests.get(https://www.python.org)print(response.status_code)# 200print(response.encoding)# utf-8print(response.text[:200])# HTML内容# POST请求responserequests.post(https://example.com/login,data{user:test})# 其他请求方法requests.put(https://api.example.com/resource/1,json{name:new_name})requests.delete(https://api.example.com/resource/1)请求参数的几种传递方式# 方式1: params参数(GET请求)params{keyword:Python,page:2}responserequests.get(https://example.com/search,paramsparams)print(response.url)# https://example.com/search?keywordPythonpage2# 方式2: data参数(POST表单)data{username:user,password:pass}responserequests.post(https://example.com/login,datadata)# 方式3: json参数(POST JSON)payload{action:search,keyword:Python}responserequests.post(https://api.example.com/data,jsonpayload)# 方式4: 请求体raw数据importjson responserequests.post(https://api.example.com/data,datajson.dumps(payload),headers{Content-Type:application/json})请求头设置headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Accept:application/json, text/plain, */*,Accept-Language:zh-CN,zh;q0.9,Referer:https://example.com,Connection:keep-alive}responserequests.get(https://example.com/api/data,headersheaders)常见User-Agent列表importrandom USER_AGENTS[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0,Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,]defget_random_ua():returnrandom.choice(USER_AGENTS)headers{User-Agent:get_random_ua()}responserequests.get(url,headersheaders)Cookie处理# 方式1: 直接在headers中设置headers{Cookie:session_idabc123; user_id12345; tokenxyz789}responserequests.get(url,headersheaders)# 方式2: 通过cookies参数cookies{session_id:abc123,user_id:12345}responserequests.get(url,cookiescookies)# 方式3: 使用Session自动管理Cookie(最推荐)sessionrequests.Session()session.headers.update({User-Agent:Mozilla/5.0 ...})# 第一次请求: 登录login_data{username:test,password:123456}session.post(https://example.com/login,datalogin_data)# 后续请求: 自动携带Cookieresponsesession.get(https://example.com/user/orders)profilesession.get(https://example.com/user/profile)代理配置代理是突破IP封禁的常用方法。# 单一代理proxies{http:http://127.0.0.1:7890,https:http://127.0.0.1:7890}responserequests.get(url,proxiesproxies)# 带用户名密码的代理proxies{http:http://username:passwordproxy.example.com:8080,https:http://username:passwordproxy.example.com:8080}# 随机代理池PROXY_LIST[http://proxy1.example.com:8080,http://proxy2.example.com:8080,http://proxy3.example.com:8080,]defget_random_proxy():iprandom.choice(PROXY_LIST)return{http:ip,https:ip}responserequests.get(url,proxiesget_random_proxy())超时和重试importtime# 设置超时try:responserequests.get(url,timeout10)# 10秒超时# timeout(连接超时, 读取超时)responserequests.get(url,timeout(5,15))# 连接5秒,读取15秒exceptrequests.Timeout:print(请求超时)# 自动重试封装deffetch_url(url,headersNone,max_retries3,delay2):forattemptinrange(1,max_retries1):try:responserequests.get(url,headersheaders,timeout10)response.raise_for_status()# 非2xx状态码抛出异常returnresponseexceptrequests.Timeout:print(f超时,第{attempt}次重试)exceptrequests.HTTPErrorase:print(fHTTP错误{e.response.status_code})ife.response.status_codein[403,404]:returnNone# 这类错误重试无意义exceptrequests.RequestExceptionase:print(f请求异常:{e})ifattemptmax_retries:time.sleep(delay*attempt)# 递增延迟returnNone响应数据处理responserequests.get(https://example.com)# 自动检测编码print(response.encoding)# 检测到的编码print(response.apparent_encoding)# 更准确的编码检测# 设置编码解决乱码response.encodingutf-8htmlresponse.text# 二进制数据(图片、PDF等)image_responserequests.get(https://example.com/image.jpg)withopen(image.jpg,wb)asf:f.write(image_response.content)# 大文件流式下载withrequests.get(https://example.com/large_file.zip,streamTrue)asr:r.raise_for_status()withopen(large_file.zip,wb)asf:forchunkinr.iter_content(chunk_size8192):f.write(chunk)print(下载完成)1.3 实战综合运用GET/POST请求下面是一个模拟搜索引擎关键词搜索和翻页爬取的完整示例。importrequestsimporttimeimportrandomfrombs4importBeautifulSoupclassSimpleSpider:def__init__(self):self.sessionrequests.Session()self.session.headers.update({User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36,Accept-Language:zh-CN,zh;q0.9})self.results[]defsearch(self,keyword,max_pages5):print(f开始爬取关键词:{keyword})forpageinrange(1,max_pages1):print(f正在爬取第{page}页...)params{q:keyword,page:page,size:20}responseself._fetch(https://example.com/search,paramsparams)ifnotresponse:print(f第{page}页获取失败,跳过)continueitemsself._parse(response.text)self.results.extend(items)print(f第{page}页提取{len(items)}条数据)# 随机延时,避免过快请求sleep_timerandom.uniform(1.0,2.5)time.sleep(sleep_time)returnself.resultsdef_fetch(self,url,paramsNone):try:responseself.session.get(url,paramsparams,timeout10)response.raise_for_status()returnresponseexceptExceptionase:print(f请求失败:{e})returnNonedef_parse(self,html):soupBeautifulSoup(html,lxml)items[]foriteminsoup.select(div.result-item):items.append({title:item.select_one(h3).text.strip(),url:item.select_one(a)[href],summary:item.select_one(p.summary).text.strip()})returnitemsdefsave(self,filenameresults.json):importjsonwithopen(filename,w,encodingutf-8)asf:json.dump(self.results,f,ensure_asciiFalse,indent2)print(f已保存{len(self.results)}条数据到{filename})# 使用示例spiderSimpleSpider()dataspider.search(Python爬虫教程,max_pages3)spider.save()