利用python标准库中的urllib.request模块可以编写基础网络爬虫来下载网页。核心做法是调用urlopen()函数传入目标url,读取响应对象的read()方法获取字节流,并指定编码解码为字符串。若请求被服务器拒绝(如状态码非200),需检查httperror异常或状态属性以处理错误。

如何处理HTTP请求中的异常状态码
当urlopen()遇到4xx或5xx错误时,会抛出HTTPError异常。通过捕获该异常,可以访问其code和reason属性来获取具体的错误信息,从而区分是客户端错误还是服务器错误。

import urllib.request
import urllib.error
def fetch_with_error_handling(url):
try:
response = urllib.request.urlopen(url)
return response.read().decode('utf-8')
except urllib.error.HTTPError as e:
print(f"HTTP Error: {e.code} - {e.reason}")
return None
except urllib.error.URLError as e:
print(f"URL Error: {e.reason}")
return None
html = fetch_with_error_handling('https://httpbin.org/status/404')如何设置自定义请求头模拟浏览器
许多网站会检查User-Agent头来阻止简单的脚本访问。可以通过创建Request对象并添加headers字典来伪装成浏览器,从而成功获取网页内容。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

import urllib.request
def fetch_with_headers(url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
req = urllib.request.Request(url, headers=headers)
try:
response = urllib.request.urlopen(req)
return response.read().decode('utf-8')
except Exception as e:
print(f"Failed: {e}")
return None
html = fetch_with_headers('https://example.com')基于程序中返回的HTML字符串长度判断页面是否有效
在爬取过程中,可以通过检查返回的HTML字符串长度来判断页面是否有效。如果长度为0或极小,可能意味着页面为空或请求失败。以下代码展示了如何结合长度检查来验证页面内容。
import urllib.request
def check_page_length(url):
try:
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
if len(html) > 100: # 假设有效页面至少100字符
return True, html
else:
return False, "Page too short or empty"
except Exception as e:
return False, str(e)
is_valid, content = check_page_length('https://example.com')
print(f"Valid: {is_valid}, Content Length: {len(content) if isinstance(content, str) else 0}")

















