python爬取HTML网页
来源:互联网 发布:淘宝有哪些部门 编辑:程序博客网 时间:2024/05/17 06:29
记录python正则学习中遇到的问题,以供日后参考。
例如,使用python正则爬取freebuf最新内容title和URL
思路:查看源代码,发现所有最新内容title和url都在 “news-info”和”news-img”这两个类中,通过一次性定位到这两个类中的内容来进行爬取。
难点主要是不会构造正则表达式,经过学习可写出来,但是较为繁琐。
#coding=utf-8 import reimport requestsfrom distutils.filelist import findallcontents= requests.get('http://www.freebuf.com/').text pattern=re.compile('<div class="news-img.*?<a target="_blank" href="(.*?)">.*?<\/a>.*?<div class="news-info.*?<dl>.*?<dt>.*?<a.*?>(.*?)<\/a>',re.S)items = re.findall(pattern,contents)for item in items: print item[1].strip()+'\n'+item[0]
使用BeautifulSoup更简单一些,代码如下:
#coding=utf-8 import requestsfrom bs4 import BeautifulSoup contents= requests.get('http://www.freebuf.com/').textsoup = BeautifulSoup(contents,"html.parser") for tag in soup.select('.news-img'): name = tag.find('img', class_='img-responsive').get('title') url = tag.find('a').get('href') print (name + '\n' + url)
首先定位到“.news-img”,然后在“class_=’img-responsive”中寻找title内容,同理寻找href。
阅读全文
0 0
- python爬取HTML网页
- Python 爬取网页HTML代码
- Python-爬取HTML网页数据
- python爬爬爬之单网页html页面爬取
- python爬取网页
- Python 网页爬取
- python 爬取网页正文
- python 多线程网页爬取
- python爬取网页信息
- python爬取网页图片
- 学习python爬取网页
- Python爬取简单网页
- python爬取网页内容
- python爬取网页图片
- Python爬取网页数据
- Python爬取网页图片
- Python爬取网页图片
- Python-爬取网页信息
- 冒泡排序
- eclipse新建项目时显示no applicable items
- Linux手动添加SWAP分区
- Tomcat启动时卡在“INFO: Deploying web application directory ......”的解决方法
- 实验过程中一些不成体系的小Tips
- python爬取HTML网页
- MFC生成的exe文件在别人电脑无法正常运行
- Tomcat 强制使用https协议后 中文乱码问题
- Android使用VideoView播放网络视频
- 可变参数创建Java中集合的工厂方法
- android中getLocationInWindow 和 getLocationOnScreen的区别
- Jmeter调试工具---Debug Sampler
- php常用数组处理
- Intellij Idea安装主题包