python 爬虫实战 | 下载一本小说2

该篇内容展示了如何在jupyternotebook环境下编写Python爬虫,处理中文乱码问题,从目录页获取链接列表,然后批量下载和提取网页文本。使用requests库获取页面,BeautifulSoup解析HTML,通过正则表达式清洗数据,最终将内容写入文件。

给出第二个爬虫实例。

  • 使用 jupyter notebook 环境运行。
  • 遇到中文乱码问题。

1 获取url list

import requests
import re
from bs4 import BeautifulSoup
import time,random

# 从目录页,获取链接列表
page = 'https://www.tycqzw.la/47_47107/';
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
}
respose=requests.get(page, headers);
assert respose.status_code==200,'Error: requests.get'

respose.encoding='utf-8'  #主动设置编码
#respose.text

from bs4 import BeautifulSoup
soup=BeautifulSoup(respose.text,"lxml")
arr=soup.find_all("div", attrs={"id":"list"})[0].find_all("a")
arr

输出:

[<a href="/47_47107/10393894.html">第543章 尾声</a>,
 <a href="/47_47107/10393893.html">第542章 忽离忽别负华年(2)</a>,
 <a href="/47_47107/10393892.html">第541章 忽离忽别负华年(1)</a>,
 <a href="/47_47107/10393891.html">第540章 你是我的(2)</a>,

arr2=arr[9:]
len(arr2) #543

2. 提取文本

import requests
import re
from bs4 import BeautifulSoup
import time,random

# 为防被封,不能高频访问:模拟用户的点击间隔
def pause(seconds=2):
    #随机时间段后[2s,12s]执行
    pause=seconds+3*random.random()
    print('  sleep '+str(pause) + "second \n")
    time.sleep(pause)


def write2file(url, title):
    #1. get response
    headers = {
        "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
    }
    respose=requests.get(url, headers);
    respose.encoding='utf-8'
    assert respose.status_code==200,'Error: requests.get'


    #2. get info
    soup=BeautifulSoup(respose.text,"lxml")
    patterns=soup.find_all("div", attrs={"id": "content"} )[0]
    
    #3. write to file
    fw=open('novel2.txt','a');
    fw.write(title+"\n");
    
    for item in patterns:
        text=item.string
        if None != text and text.strip() != "": #跳过全是空格的行
            text=re.sub("校花的全能保安", "", text)
            text=re.sub("推荐都市大神老施新书:", "", text)
            #text=re.sub("章(.*?)\s{3,}", "章\\1\\n", text)
            text=re.sub("\s{4,}", "  ", text)
            #print("> "+ text)
            fw.write(text)
    fw.write(url+"\n\n\n################\n")

# url="https://www.tycqzw.la" +arr2[0].get("href")
# title=arr2[0].string;

# print(title+"\n"+url)
# write2file(url, title)
# print("done")

3. 批量下载和提取

# get url
i=0
for ele in arr2:
    i=i+1
    url1="https://www.tycqzw.la" +ele.get("href");
    title1=ele.string;
    print( str(i) +" "+  url1+ " " + title1)
    write2file(url1, title1)
    pause(0.5)
print("end")

这一次有 543 个,需要的时间更多了。耐心等待即可。
针对每个网站,都要重新设计信息提取部分的代码。
最后的文本有 2.5M。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值