''' 访问菜鸟教程(https://www.runoob.com),爬取其Python3实例模块的题目内容,按照以下格式爬取输出内容: 1、Python Hello World实例 以下实例为学习Python的第一个实例, 即如何输出"Hello World!": 2、Python 数字求和 以下实例为通过用户输入两个数字,并计算两个数字之和: ''' import requests from lxml import html url='https://www.runoob.com/python3/python3-examples.html' r = requests.get(url) r.encoding=r.apparent_encoding html1=html.etree.HTML(r.text) all=html1.xpath('//*[@id="content"]/ul/li') for i in range(len(all)): biaoti=all[i].xpath('./a/text()')[0] #print(biaoti) #爬出来是 Python Hello World 实例 #但要求是 1、Python Hello World实例 title=biaoti.replace('Python',str(i+1)) #print(title) href=all[i].xpath('./a/@href')[0] #print(href) #爬取出来的第一个url是 /python3/python3-helloworld.html 但是其他的是 python3-add-number.html因此需要替换 ''' 方法一 href1=href.replace('/python3/','') print(href1) ''' '''方法二''' import re HREF=re.sub('^/python3/','',href) #print(HREF) new_url='https://www.runoob.com/python3/'+str(HREF) #print(new_url) res=requests.get(new_url) res.encoding=res.apparent_encoding html2=html.etree.HTML(res.text) neirong=html2.xpath('//*[@id="content"]/p[2]/text()')[0] #print(neirong) print(title,'\n',neirong)