大家好,小编来为大家解答以下问题,用正则表达式爬取数据,网络爬虫正则表达式,现在让我们一起来看看吧!

from urllib import request
import re
#定义URL
url='https://tieba.baidu.com/fkw=%B6%CE%D7%D3&fr=ala0&tpl=5&dyTabStr=MCw2LDIsNCw1LDMsMSw4LDcsOQ%3D%3D'
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'<a rel="noopener".*?title=(.*?)\s.*?>(.*?)</a>')
#匹配html
items=re.findall(pattern,content)
#打印解码的内容
for i in items:
print(i[0]+'\t'+i[1])
except request.URLError as e:
if hasattr(e,'code'):
print(e.code)
if hasattr(e,'reasson'):
print(e.reason)
本文介绍了如何使用Python的urllib和re模块通过正则表达式从指定URL抓取网页数据,包括设置请求头、解析HTML内容中的链接和标题信息。
2484

被折叠的 条评论
为什么被折叠?



