python 爬取数据



提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.引入库

导入requests库和etree库

import requests
from lxml import etree

2.获取网页的HTML

html=requests.get('https://so.gushiwen.org/shiwenv_a1e7559dada7.aspx').text
#requests的get请求,直接获取网页的HTML

3.获取xpath

这个网站没有反爬,所有可以直接获取
古诗文网爬取内容页面

tree=etree.HTML(html)
datas=tree.xpath('//*[@id="sonsyuanwen"]/div[1]')
#图片中的第一个箭头的位置

爬取的古诗

for data in datas:
    bt=data.xpath('./h1/text()')[0] #标题
    sr=data.xpath('./p/a[1]/text()')[0] #诗人
    sd=data.xpath('./p/a[2]/text()')[0] #时代
    print(bt+"\n"+sr+"\t"+sd)
    #诗句
    br=tree.xpath('//*[@id="contsona1e7559dada7"]')
    for brs in br:
        sc1=brs.xpath('./text()[1]')[0]
        sc2 = brs.xpath('./text()[2]')[0]
        sc3 = brs.xpath('./text()[3]')[0]
        sc4 = brs.xpath('./text()[4]')[0]
        print(sc1+"\n"+sc2+"\n"+sc3+"\n"+sc4)

4.存储为txt文档

        with open("古诗.txt","w", encoding="utf-8",newline='')as f:
            f.write(bt+"\n"+sr+"\t"+sd+sc1+"\n"+sc2+"\n"+sc3+"\n"+sc4)

总结

整体代码:

import requests
from lxml import etree

html=requests.get('https://so.gushiwen.org/shiwenv_a1e7559dada7.aspx').text

tree=etree.HTML(html)
data=tree.xpath('//*[@id="sonsyuanwen"]/div[1]')
for datas in data:
    bt=datas.xpath('./h1/text()')[0]
    sr=datas.xpath('./p/a[1]/text()')[0]
    sd=datas.xpath('./p/a[2]/text()')[0]
    print(bt+"\n"+sr+"\t"+sd)
    br=tree.xpath('//*[@id="contsona1e7559dada7"]')
    for brs in br:
        sc1=brs.xpath('./text()[1]')[0]
        sc2 = brs.xpath('./text()[2]')[0]
        sc3 = brs.xpath('./text()[3]')[0]
        sc4 = brs.xpath('./text()[4]')[0]
        print(sc1+"\n"+sc2+"\n"+sc3+"\n"+sc4)

        with open("古诗.txt","w", encoding="utf-8",newline='')as f:
            f.write(bt+"\n"+sr+"\t"+sd+sc1+"\n"+sc2+"\n"+sc3+"\n"+sc4)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值