20行代码简单python爬虫,爬虫实例

编程知识 行业动态 更新时间:2024-06-13 00:17:58

目录

前言

函数介绍

库函数介绍 

函数1 

完整代码 

总结



前言

小说看不过瘾,下载下来慢慢看,python爬虫五分钟轻松下载小说_novel is so frustrating!


函数介绍

函数功能简单介绍


库函数介绍 

import requests#请求网页
from lxml import etree#对网页进行解析

函数功能介绍 


函数1 

def getdata(url):
    html=requests.get(url).text
    # print(html)
    doc=etree.HTML(html)#构造xpath的解析对象
    contents=doc.xpath('//*[@class="cf"]/li')
    # print(contents)
    for content in contents:
        links=content.xpath('h2/a/@href')
        for link in links:
            hurl="https:"+link#小说某一章的网址
            html=requests.get(hurl).text#获取到源代码
            doc=etree.HTML(html)#构造xpath解析对象
            title=doc.xpath('//*[@class="text-wrap"]/div/div[1]/h3/span[1]/text()')
            content=doc.xpath('//*[@class="read-content j_readContent"]/p/text()')
            with open('novel/%s.txt'%title[0],mode='w',encoding='utf-8') as f:
                for abd in content:
                    f.write(abd)

函数功能比较简单,所以就没有对其中的保存小说的函数进行封装,有兴趣的可以自己尝试一下。


完整代码 


#获取起点小说的爬虫程序
#倒推法
import requests
from lxml import etree
url="https://book.qidian/info/1979049/#Catalog"#小说的网址
def getdata(url):
    html=requests.get(url).text
    # print(html)
    doc=etree.HTML(html)#构造xpath的解析对象
    contents=doc.xpath('//*[@class="cf"]/li')
    # print(contents)
    for content in contents:
        links=content.xpath('h2/a/@href')
        for link in links:
            hurl="https:"+link#小说某一章的网址
            html=requests.get(hurl).text#获取到源代码
            doc=etree.HTML(html)#构造xpath解析对象
            title=doc.xpath('//*[@class="text-wrap"]/div/div[1]/h3/span[1]/text()')
            content=doc.xpath('//*[@class="read-content j_readContent"]/p/text()')
            with open('novel/%s.txt'%title[0],mode='w',encoding='utf-8') as f:
                for abd in content:
                    f.write(abd)
a=getdata(url)

函数功能介绍 

总结


学习了entree对网页源码进行解析,requests库对网页进行解析获得源码,同时代码中还用到了获取标签xpath的方法,xpath的解析将在下一篇文章进行解析。

更多推荐

20行代码简单python爬虫,爬虫实例

本文发布于:2023-03-26 02:04:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/bb6189d365b77e3467e1cb07ee6641ef.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:爬虫   实例   代码   简单   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!