python爬虫3:批量爬取小说章节

爬虫

爬取凡人小说

import os.path
import requests
from fake_useragent import UserAgent
from lxml import etree
from bs4 import BeautifulSoup

def fanrenxiuxianzhuan(number):
    url = 'http://www.156n.com/html/0/29/'+str(number)+'.html'#修仙小说url
    ua = UserAgent() #随机请求头
    head = ua.chrome
    headers = {
        'user-agent': head
    }
    response = requests.get(url, headers=headers) #请求
    html = etree.HTML(response.text)
    zhangjie = html.xpath("//div[@class='bookname']/h1/text()")#章节名称
    txt = html.xpath("//div[@id='content']/p/text()")   #具体小说文字
    fanrentxt = '修仙小说'#文件夹
    #保存文件txt
    fanren = '烦人休闲传1.txt' #保存文件txt
    if not os.path.exists(fanrentxt):
        os.mkdir(fanrentxt)
    address = os.getcwd() + "\\" + fanrentxt 
    with open(address + '/' + fanren, 'a+', encoding='utf-8') as f:
        # 爬取的第一章标题的类型为'list',需要转为字符串
        f.write('------------------------------------------------------ ' + str(zhangjie) + '------------------------------------------------------ '+'\n' )
    #循环遍历保存章节内容
    for i in txt:
        with open(fanrentxt + '/' + fanren, 'a+', encoding='utf-8') as f:
            f.write(i + '\n')
for i in range(1,101):#爬取修仙前100章
    # 这里的第一章为1591,第十章为15910,第一百章为159100,第一千章为1591000,所以这里需要转字符串进行拼接
    fanrenxiuxianzhuan('159'+str(i))
    print('------------------------第'+str(i)+'章下载完成------------------------')

最终效果展示:
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Python 爬虫教程,可以批量爬取指定网站的图片: 首先,我们需要安装 requests 和 BeautifulSoup 这两个库。可以通过以下命令进行安装: ``` pip install requests pip install beautifulsoup4 ``` 接下来,我们需要编写代码。以下是一个示例代码,可以爬取指定网站的图片并保存到本地: ```python import requests from bs4 import BeautifulSoup import os # 爬取图片的网站 url = "https://www.example.com/" # 请求头,模拟浏览器访问 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} # 发送请求,获取网页内容 response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # 创建保存图片的文件夹 if not os.path.exists("images"): os.makedirs("images") # 遍历所有的图片标签,获取图片链接并保存到本地 for img in soup.find_all("img"): img_url = img.get("src") if img_url.startswith("http"): response = requests.get(img_url) with open("images/" + os.path.basename(img_url), "wb") as file: file.write(response.content) print("已保存图片:", img_url) ``` 在上述代码中,我们首先定义了要爬取的网站的 URL。然后,我们使用 requests 库发送一个 GET 请求,获取网页的 HTML 内容。接着,我们使用 BeautifulSoup 库对 HTML 进行解析,获取所有的图片标签。最后,我们使用 requests 库再次发送 GET 请求,获取图片的二进制数据,并保存到本地的 images 文件夹中。 注意,这里我们使用了一个 if 判断来过滤掉非 HTTP 开头的图片链接,以避免出现下载错误的情况。 为了更好的用户体验,代码中还加入了一些注释,方便大家理解。 希望这个简单的 Python 爬虫教程能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值