python爬虫之爬取文本内容(2)

一、基本案例

cpp 复制代码
#注意:需要将requests包换成2.27.1
#中文编码gbk也可能是utf-8
import requests
#from bs4 import BeautifulSoup

if __name__ == '__main__':
    url = 'https://www.biqg.cc/book/6909/1.html'#目标访问网站url
    #伪装头信息的引入
    header = {"User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0"}
    req = requests.get(url=url,headers = header) #返回爬取网站信息
    req.encoding = 'utf-8'  #查看head中charset可以查找到编码信息
    html = req.text #转化为文本
    print(html)

二、升级案例

cpp 复制代码
# import bs4 from BeautifulSoup
# #html接上文中的已爬取得到的全部信息
#  bes= BeautifulSoup(html,"lxml")#通过lxml方式解析获取网页中文本信息
#  text = bes.find("div", id = "content"[,class_ = "<class的名称>"]) #解析text中,提取标签为"div"内id = "content"全部信息,也可解析提取class = <某名称>的内容信息


import requests
from bs4 import BeautifulSoup

if __name__ == '__main__':
    url = 'https://www.biqg.cc/book/6909/1.html'#目标访问网站url
    header = {"User-Agent":
                  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0"}
    req = requests.get(url=url,headers = header)
    req.encoding = 'utf-8'
    html = req.text
    bes = BeautifulSoup(html,"lxml")
    texts = bes.find("div", class_="content")
    print(texts)

三、最终案例

cpp 复制代码
import requests
from bs4 import BeautifulSoup

if __name__ == '__main__':
    url = 'https://www.biqg.cc/book/6909/1.html'#目标访问网站url
    header = {"User-Agent":
                  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0"}
    req = requests.get(url=url,headers = header)
    req.encoding = 'utf-8'
    html = req.text
    bes = BeautifulSoup(html,"lxml")
    texts = bes.find("div", class_ = "Readarea ReadAjax_content")
    # print(texts)
    texts_list = texts.text.split("\xa0" * 4) #texts.text.split("\xa0" * 4)会将texts.text按照\xa0\xa0\xa0\xa0进行分割,得到一个字符串列表,存储在texts_list中。
    texts_list = texts.text.split("\u3000" * 2)
    # print(texts_list)

    with open("D:/novel.txt","w") as file:    ##打开读写文件,逐行将列表读入文件内
        for line in texts_list:
            file.write(line+"\n")
相关推荐
NiceCloud喜云2 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
AI玫瑰助手2 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
weixin_468466852 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
油炸自行车2 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋2 小时前
C++14特性
开发语言·c++·c++14特性
小糖学代码3 小时前
LLM系列:环境搭建:5.Python-dotenv 环境变量管理
人工智能·python·深度学习·神经网络
智慧物业老杨3 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
橙橙笔记3 小时前
Python的学习第一部分
python·学习
JAVA社区4 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子4 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php