1 from lxml import etree
2
3 r = '''
4 <div class="tabsConItem syllabus">
5 <ul >
6 <li class="item lesson" >
7 <div class="main"><a href="https://edu.51cto.com/center/course/lesson/index? title="第一个python程序与数据存储-1" target="_blank">第一个python程序与数据存储-1</a></div>
8 </li>
9 <li class="item lesson" >
10 <div class="main"><a href="https://edu.51cto.com/center/course/lesson/index? title="第一个python程序与数据存储-2" target="_blank">第一个python程序与数据存储-2</a></div>
11 </li>
12 <li class="item lesson" >
13 <div class="main"><a href="https://edu.51cto.com/center/course/lesson/index? title="第一个python程序与数据存储-3" target="_blank">第一个python程序与数据存储-3</a></div>
14 </li>
15 <li class="item lesson" >
16 <div class="main"><a href="https://edu.51cto.com/center/course/lesson/index? title="第一个python程序与数据存储-4" target="_blank">第一个python程序与数据存储-4</a></div>
17 </li>
18 <li class="item lesson" >
19 <div class="main"><a href="https://edu.51cto.com/center/course/lesson/index? title="第一个python程序与数据存储-5" target="_blank">第一个python程序与数据存储-5</a></div>
20 </ul>
21 <div >加载中</div>
22 <div ></div>
23 </div>'''
24 '''
25
26 '''
27 def parse_text():
28 html = etree.HTML(r) # 这个底层已经设定好html解析器,不需要重新设置
29 # 使用etree将爬虫爬取保存成字符串格式的文件重新转换成HTML格式的文件以便用xpath语法提取信息
30 print(etree.tostring(html, encoding='utf-8').decode('utf-8'))
31 def parse_lagou_file():
32 #拉钩网的语法不想腾讯的那么规范,因此需要调用etree.HTMLParser生成一个专门用来解析html的解析器正常解析
33 parse = etree.HTMLParser(encoding="UTF-8")
34 html2 = etree.parse('lagou.html',parser=parse) #读取文件方式解析
35 #etree.parse('lagou.html',parser=parse)默认是使用XML解析器的
36 print(etree.tostring(html2,encoding='utf-8').decode('utf-8'))
37 if __name__ == '__main__':
38 parse_lagou_file()