扫码关注官方订阅号
小伙看你根骨奇佳,潜力无限,来学PHP伐。
好像用Python的库直接解析HTML更简单
Python
HTML
建议使用beautifulsoup库解析,和前端操作dom类似解析html
beautifulsoup
不需要使用正则,最好用BeautifulSoup解析HTML文档:
BeautifulSoup
from bs4 import BeautifulSoup html = ''' <p class="list_item clearfix"> .........你的html文档 </p> ''' soup = BeautifulSoup(html) tags = soup.find_all('p', class_='item_top') news_list = [] for tag in tags: news_dict = {} news_dict['news_title'] = tag.h2.string news_dict['news_time'] = tag.span.string news_dict['news_abstract'] = tag.p.next_element news_dict['news_url'] = tag.h2.a.get('href') news_list.append(news_dict)
最终运行结果,每个新闻一个字典,所有字典在一个列表里:
print(news_list) [ { 'news_abstract': '[摘要:8月30日晚间公布的格力电器上半年财报无疑给董明珠浇了一盆冷水。虽然董明珠嘴上仍在硬撑,但她的底气明显不足了。因为,格力的主营业务——空调出问题了。当格力开始不谈承诺的时候,董明珠最应该干的事,是静下心来好好反思,而不是把更多的心思花在无聊的口水战和吹牛逼 ...', 'news_url': 'http://money.163.com/15/0902/09/B2GEL9V8002551G6.html', 'news_time': '2015-09-02 09:20:55', 'news_title': '主营业务负增长 董明珠还自信?' }, { 'news_abstract': '[摘要:中国手机全球化版图扩张中,已经完成了两个阶段,国内市场红海一片,几乎没有太多眷恋;欧美发达国家,市场如堡垒般稳固,而且面临专利、渠道等麻烦,败走麦城似乎是命中注定的事儿。]原标题:[亦观察] No.616\xa0中国手机的非洲历险记如今,中国手机正悄然转移重点,把 ...', 'news_url': 'http://money.163.com/15/0831/11/B2BGVVQ0002551G6.html', 'news_time': '2015-08-31 11:25:30', 'news_title': '中国手机的非洲历险记' } ]
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
好像用
Python的库直接解析HTML更简单建议使用
beautifulsoup库解析,和前端操作dom类似解析html不需要使用正则,最好用
BeautifulSoup解析HTML文档:最终运行结果,每个新闻一个字典,所有字典在一个列表里: