(以“搞笑吧”为例)
from urllib import request import re page=100 url='https://tieba.baidu.com/f?kw=%E6%AE%B5%E5%AD%90&ie=utf-8&pn='+str(page) try: #请求头 headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36'} #定义请求,传入请求头 req=request.Request(url,headers=headers) #打开请求 resp=request.urlopen(req) #打印返回信息 content=resp.read().decode('utf-8') print(content) #正则表达式 #pattern=re.compile(r'<title>(.*)</title>') #pattern=re.compile(r'<a.*?title=(.*?)\s') pattern=re.compile(r'<a rel="noopener".*?title=(.*?)\s.*?>(.*?)</a>') #匹配 HTML items=re.findall(pattern,content) #打印解析内容 for i in items: print(i[0]+' \t'+i[1]) #print(i) except request.URLError as e: #打印响应码 if hasattr(e,'code'): print(e.code) #打印异常原因 if hasattr(e,'reson'): print(e.reason)