时间:2021-05-22
如下所示:
from bs4 import BeautifulSouppath = './web/new_index.html'with open(path, 'r') as f: Soup = BeautifulSoup(f.read(), 'lxml') titles = Soup.select('ul > li > div.article-info > h3 > a')for title in titles: print(title.text)输出:Sardinia's top 10 beachesHow to get tannedHow to be an Aussie beach bumSummer's cheat sheet#其中titles = Soup.select('ul > li > div.article-info > h3 > a')#等效titles = Soup.select('h3 a')print(title.text)#等效print(title.get_text())print(title.string)也可以使用以下代码
import bs4 path = './web/new_index.html' with open(path, 'r') as f: Soup = bs4.BeautifulSoup(f.read(), 'lxml') titles = Soup.select('h3 a') for title in titles: print(title.string)Html原文:
<html><head> <link rel="stylesheet" type="text/css" href="new_blah.css" rel="external nofollow" ></head><body> <div class="header"> <img src="images/blah.png"> <ul class="nav"> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Home</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Site</a></li> <li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Other</a></li> </ul> </div> <div class="main-content"> <h2>Article</h2> <ul class="articles"> <li> <img src="images/0001.jpg" width="100" height="91"> <div class="article-info"> <h3><a href="" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >Summer's cheat sheet</a></h3> <p class="meta-info"> <span class="meta-cate">bay</span> <span class="meta-cate">boat</span> <span class="meta-cate">beach</span> </p> <p class="description">choosing a beach in Cape Cod</p> </div> <div class="rate"> <span class="rate-score">3.0</span> </div> </li> </ul> </div> <div class="footer"> <p>© Mugglecoding</p> </div></body></html>以上这篇Python读取本地文件并解析网页元素的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
Python2.7编写的读取html中指定元素,并生成excle文件复制代码代码如下:#coding=gbkimportstringimportcodecsim
XmlReader通过向前读取文档并识别读取到的元素,为我们提供了一种消耗资源最少的方式来解析XML数据。很多时候我们都是利用XmlReader来对XML文件的
Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Sesssi
所使用python环境为最新的3.6版本Python中几种对文件的操作方法:将A文件复制到B文件中去(保持原来格式)读取文件中的内容,返回List列表(加载本地
今天,在完成一个小的python习题,习题的主要内容是读取一个帮助模块,并保存到本地文件。知道是用pydoc进行模块的读取,但是在windows系统下,调用os