python爬取单章节内容

这篇博客介绍了如何使用Python进行数据解析,包括XPath、CSS选择器和正则表达式(re)来抓取单个章节的内容。讨论了何时使用CSS和XPath,以及如何通过它们提取数据。同时,讲解了如何将列表转换为字符串、保存数据的方法,以及自动创建文件夹的技巧。
摘要由CSDN通过智能技术生成

爬取单个章节内容

数据解析

1、xpath,css,re

什么时候使用css和xpath?无论css还是xpath都可以跨标签提取。
css选择器,根据标签属性提取数据
xpath,根据标签节点提取数据。
selector = parsel.Selector(reponse.text)#将reponses.text 字符串数据,转成可解析的对象。
当得到的数据有标签的时候。
re:当没有办法使用标签提取的时候,使用re。可以直接对字符串数据进行提取。
selector.css(’ ::text’).get()

使用css获取数据

# 爬取网页上某个章节的内容
import requests
import parsel
from bs4 import BeautifulSoup

url = 'https://hanyu.baidu.com/shici/detail?pid=fe2332c606714577b32b30200d8440b6&from=kg0'
html = requests.get(url)
# print(html.text)
# 将字符串数据转换为可解析的对象。
selector = parsel.Selector(html.text)
# 得到title,选中标题,右键,复制selector path
title = selector.css('#poem-detail-header > h1::text').get()
print(title)

使用xpath获取数据

# 爬取网页上某个章节的内容
import requests
import parsel
from bs4 import BeautifulSoup

url = 'https://hanyu.baidu.com/shici/detail?pid=fe2332c606714577b32b30200d8440b6&from=kg0'
html = requests.get(url)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python 爬取 VIP 章节的方法有很多种,这介绍一种比较常用的方法: 1. 首先需要安装 requests 和 BeautifulSoup 库,可以使用 pip install requests 和 pip install beautifulsoup4 命令进行安装。 2. 使用 requests 库发送 GET 请求获取网页内容,例如: ``` import requests url = 'https://www.example.com/vip/chapter1' 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) html = response.text ``` 其中,url 是需要爬取的网页地址,headers 是请求头,用于模拟浏览器发送请求。 3. 使用 BeautifulSoup 库解析网页内容,例如: ``` from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') content = soup.find('div', class_='vip-content') ``` 其中,html 是上一步获取到的网页内容,'html.parser' 是解析器类型,'div' 是需要查找的标签名,class_='vip-content' 是该标签的 class 属性值。 4. 将获取到的内容保存到本地文件中,例如: ``` with open('chapter1.txt', 'w', encoding='utf-8') as f: f.write(content.text) ``` 其中,'chapter1.txt' 是保存的文件名,'w' 表示写入模式,encoding='utf-8' 表示使用 UTF-8 编码保存文件,content.text 是获取到的内容。 以上就是 Python 爬取 VIP 章节的基本方法,当然具体实现还需要根据网站的具体情况进行调整。如果您有其他问题或需要更详细的解释,请随时提出。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值