runoob爬取python模块实例

'''
访问菜鸟教程(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)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值