Pythont 爬虫

红楼梦全书爬虫

import requests
# 导入模块
from lxml import etree
def pater(url):
    # 头部文件
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
    }
    # 给服务器发送请求
    response = requests.get(url,headers=headers)
    # 返回数据 decode()可以把字节串(bytes)解码为字符串(str)
    return response.content.decode()
#
url = "https://www.shicimingju.com/book/hongloumeng.html"
text = pater(url)
html = etree.HTML(text)
book_names = html.xpath("//h1//text()")[0]
titles = html.xpath('//div[@class="book-mulu"]//a//text()')
hears = html.xpath('//div[@class="book-mulu"]//a//@href')
domin = "https://www.shicimingju.com"

for url in hears:
    title = titles[hears.index(url)]
    print(title)
    url = domin + url
    text = pater(url)
#     # 转成xpath用来解析的对象element
    html = etree.HTML(text)
    content=html.xpath("//div[@class='chapter_content']//p/text()")
    with open (book_names+".txt",'a',encoding='utf-8') as f:
        f.write(title+'\n')
        for con in content:
            f.write(con + '\n')
        print(title)

代码解释

  1. import requests:导入requests库,用于发送HTTP请求。

  2. from lxml import etree:从lxml库中导入etree模块,用于解析HTML文档。

  3. def pater(url):定义一个名为pater的函数,接收一个url参数。

  4. headers = {...}:设置请求头,模拟浏览器访问网站。

  5. response = requests.get(url, headers=headers):使用requests库的get方法发送GET请求,获取网页内容。

  6. return response.content.decode():将获取到的网页内容(字节串)解码为字符串,并返回。

  7. url = "https://www.shicimingju.com/book/hongloumeng.html":设置要爬取的网址。

  8. text = pater(url):调用pater函数,传入url参数,获取网页内容。

  9. html = etree.HTML(text):将获取到的网页内容转换为etree对象,方便后续解析。

  10. book_names = html.xpath("//h1//text()")[0]:使用XPath表达式提取网页中的书名。

  11. titles = html.xpath('//div[@class="book-mulu"]//a//text()'):提取章节标题。

  12. hears = html.xpath('//div[@class="book-mulu"]//a//@href'):提取章节链接。

  13. domin = "https://www.shicimingju.com":设置网站域名,用于拼接完整的章节链接。

  14. for url in hears::遍历章节链接列表。

  15. title = titles[hears.index(url)]:根据当前链接在列表中的索引,获取对应的章节标题。

  16. print(title):打印章节标题。

  17. url = domin + url:拼接完整的章节链接。

  18. text = pater(url):调用pater函数,传入新的url参数,获取章节内容。

  19. html = etree.HTML(text):将获取到的章节内容转换为etree对象,方便后续解析。

  20. content = html.xpath("//div[@class='chapter_content']//p/text()"):提取章节正文内容。

  21. with open(book_names+".txt", 'a', encoding='utf-8') as f::以追加模式打开一个名为书名的txt文件,编码为utf-8。

  22. f.write(title+' '):将章节标题写入文件。

  23. for con in content::遍历章节正文内容。

  24. f.write(con + ' '):将章节正文内容写入文件。

  25. print(title):打印章节标题

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值