我的第二个Python爬虫

爬取新笔趣阁小说

上次写了一个爬取诗词名句网的小说后,发现爬虫很有意思,且我也是一个小说迷,作为学生党资金有限,经常去笔趣阁看小说,就试着写了一个爬取新笔趣阁小说的Python爬虫,因没有经过专业学习,所以还有很多不足,请见谅!

**下面是我的代码,每一步都有相应的注释**

import urllib.request
import requests
from bs4 import BeautifulSoup
import re
import time

#请求头
headers={

    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \
    (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'
}
url="https://www.xsbiquge.com/78_78513/" #小说所在地址
req=urllib.request.urlopen(url).read().decode('utf8')
res= r'<dd><a href=(.*?)>'
urls=re.findall(res,req)#正则找到href
f = open('G://元尊.txt', 'a', encoding='utf8')  #建文件夹,地址可以改
f.write('元尊')  #写入小说名字
a=int(len(urls)) #由于urls是一个列表,得到长度
for i in range(a):
  urls1=urls[i] #取出herf
  sq = urls1.replace('\"', "")#替换掉urls1两端的引号
  urlls='https://www.xxbiquge.com/'+sq #拼凑章节url

  # 对URL发起请求
  s1 = requests.Session()
  r1 = s1.get(urlls,headers=headers)
  r1.encoding = 'utf-8'

  ren = r'<meta name="keywords" content="(.*?)" />'
  name = re.findall(ren, r1.text)[0] #正则得到章节名name

  # 用BeautifulSOUP提取出章节内容
  request = urllib.request.urlopen(urlls).read().decode('utf8')
  soup = BeautifulSoup( request, 'lxml')
  ao = soup.find('div', id="content")
  lists=ao.get_text()

  f.write('\n'*4+'\t'*6+name+'\n'*2+lists) #写入章节内容#
  print('正在下载  '+name+'.......')
  time.sleep(1)#延时请求
print("下载完成")
f.close()

由于还在学习中,所以程序看着有点乱,下面是运行结果:这是运行结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
创建一个简单的Python爬虫框架,我们可以使用`requests`和`BeautifulSoup`这两个库。下面将指导您构建这样一个基本框架。 ### 第一步:安装必要的库 首先,你需要在你的环境中安装`requests` 和 `beautifulsoup4`。你可以使用pip命令安装它们: ```bash pip install requests beautifulsoup4 ``` ### 第二步:设计框架结构 我们定义一个基础的爬虫类,这个类会封装请求网页、解析HTML以及存储数据的功能。 #### 类结构说明: 1. **初始化方法** (`__init__`):设置默认参数,比如超时时间、请求头部信息等。 2. **获取网页源码** (`get_html(url)`):发送HTTP GET请求并返回响应的内容。 3. **解析HTML** (`parse_html(html_content)`):使用BeautifulSoup解析HTML内容,提取有用的数据。 4. **存储数据** (`store_data(data)`):根据需求将数据保存到文件或其他数据库。 ### 实现代码 ```python import requests from bs4 import BeautifulSoup class SimpleSpider: def __init__(self, timeout=5, headers={'User-Agent': 'Mozilla/5.0'}): self.timeout = timeout self.headers = headers def get_html(self, url): try: response = requests.get(url, headers=self.headers, timeout=self.timeout) if response.status_code == 200: return response.text else: print(f"Failed to get the HTML content with status code {response.status_code}") return None except Exception as e: print(f"Error occurred while getting the HTML content: {e}") return None def parse_html(self, html_content): soup = BeautifulSoup(html_content, "html.parser") # 这里假设页面有一个特定的标签用于抓取数据,例如所有链接 links = [a['href'] for a in soup.find_all('a')] return links def store_data(self, data): filename = "data.txt" with open(filename, 'w') as file: for item in data: file.write("%s\n" % item) # 使用示例 spider = SimpleSpider() url = "https://example.com" # 目标网站URL content = spider.get_html(url) if content is not None: parsed_data = spider.parse_html(content) spider.store_data(parsed_data) else: print("Could not fetch and process the HTML content.") ``` ### 注意事项: - 确保遵守目标网站的`robots.txt`规则和版权法律。 - 对于更复杂的爬虫,你可能还需要处理JavaScript渲染的页面、登录认证等问题。 - 考虑使用异步请求来提高速度,可以使用`asyncio`和`aiohttp`库。 以上就是一个基础的Python爬虫框架的实现,您可以根据实际需求调整和扩展功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值