Python正则抓取新闻标题和链接的方法示例
作者:我要的shine 时间:2022-05-16 06:01:31
本文实例讲述了Python正则抓取新闻标题和链接的方法。分享给大家供大家参考,具体如下:
#-*-coding:utf-8-*-
import re
from urllib import urlretrieve
from urllib import urlopen
#获取网页信息
doc = urlopen("http://www.itongji.cn/news/").read() #自己找的一个大数据的新闻网站
#抓取新闻标题和链接
def extract_title(info):
pat = '<h3><a target=\"_blank\"(.*?)</a></h3>'
title = re.findall(pat, info)
titles='\n'.join(title)
#print titles
#修改指定字符串
titles1=titles.replace('class="title"','title')
titles2=titles1.replace('>',':')
titles3=titles2.replace('href','url:')
titles4=titles3.replace('="/','"http://www.itongji.cn/')
#写入文件
save=open('xinwen.txt','w')
save.write(titles4)
save.close()
titles = extract_title(doc)
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
希望本文所述对大家Python程序设计有所帮助。
标签:Python,正则,抓取
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python selenium文件上传方法汇总
2022-12-01 04:47:29
Docker部署Python爬虫项目的方法步骤
2023-03-27 14:45:21
python编程使用PyQt创建UE蓝图
2023-11-20 14:24:58
![](https://img.aspxhome.com/file/2023/0/64690_0s.gif)
next在python中返回迭代器的实例方法
2022-10-28 12:35:41
五个方便好用的Python自动化办公脚本的实现
2022-04-13 10:10:59
![](https://img.aspxhome.com/file/2023/3/113043_0s.jpg)
python字符串循环左移
2023-08-28 19:32:13
基于python实现音乐播放器代码实例
2022-07-17 21:55:53
Python和C/C++交互的几种方法总结
2021-08-25 00:49:06
![](https://img.aspxhome.com/file/2023/3/93743_0s.png)
python实现记事本功能
2022-04-02 09:54:19
![](https://img.aspxhome.com/file/2023/1/75221_0s.gif)
python3+opencv 使用灰度直方图来判断图片的亮暗操作
2024-01-01 07:07:23
![](https://img.aspxhome.com/file/2023/2/89112_0s.jpg)
python实现磁盘日志清理的示例
2021-05-10 07:08:21
asp 正则实现清除html文本格式的函数代码
2011-03-09 11:21:00
Python random模块的使用示例
2023-08-01 16:33:48
python实战项目scrapy管道学习爬取在行高手数据
2021-03-19 01:27:19
![](https://img.aspxhome.com/file/2023/7/94107_0s.jpg)
Python+Selenium实现一键摸鱼&采集数据
2021-08-22 01:05:41
![](https://img.aspxhome.com/file/2023/2/92482_0s.gif)
你应该知道的Python3.6、3.7、3.8新特性小结
2023-10-14 02:18:37
浅论网站用户粘性的提高和增强
2008-05-15 07:14:00
整理一个asp多级树型分类问题的解决方法
2007-10-17 18:38:00
Python实现简易的图书管理系统
2021-09-12 06:06:21
![](https://img.aspxhome.com/file/2023/0/107550_0s.jpg)
基于Python3.6+splinter实现自动抢火车票
2021-04-27 21:58:15