python爬取小说(二)书籍基本信息爬取

爬完数据目录和内容后,我们来爬取书籍的基本信息。
在上篇博客的基础上,爬取书籍信息并存入字典
这里写图片描述

# -*- coding: utf-8 -*-
import urllib.request
import bs4
import re
import sqlite3

def getHtml(url):
    user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"
    headers = {"User-Agent":user_agent}
    request = urllib.request.Request(url,headers=headers)
    response = urllib.request.urlopen(request)
    html = response.read()
    return html


# 爬取整个网页
def parse(url):
    html_doc = getHtml(url)
    sp = bs4.BeautifulSoup(html_doc, 'html.parser', from_encoding="utf-8")
    return sp

# 爬取书籍基本信息
def get_book_baseinfo(url):
    # class = "info"信息获取
    info = parse(url).find('div',class_ = 'info')
    book_info = {}
    if info:
        book_info['title'] = ''
        book_info['img'] = ''
        # 标题
        book_info['title'] = info.find('h2').string
        
        # 图片链接
        img = info.find('div',class_ = 'cover')
        for im in img.children:
            # 图片地址想要访问,显然需要拼接
使用Python爬取网站信息通常会借助一些第三方库,比如`requests`用于发送网络请求,`BeautifulSoup`用于解析HTML页面。下面是一个简单的示例代码,用于爬取某个图书排行网站的信息。请注意,具体的代码会根据目标网站的结构和所需的图书信息有所不同。 ```python import requests from bs4 import BeautifulSoup # 假设我们要爬取的图书排行网址是 http://example.com/books URL = 'http://example.com/books' # 发送GET请求 response = requests.get(URL) # 检查请求是否成功 if response.status_code == 200: # 使用BeautifulSoup解析HTML内容 soup = BeautifulSoup(response.text, 'html.parser') # 假设每本书的信息包含在class为"book"的div标签内 books = soup.find_all('div', class_='book') # 遍历每本书的信息并提取 for book in books: # 假设书名在h3标签内 title = book.find('h3').text # 假设作者信息在某个特定的span标签内 author = book.find('span', class_='author').text # 打印每本书的信息 print(f"书名:{title}, 作者:{author}") else: print("网页请求失败,状态码:", response.status_code) ``` 这段代码首先发送一个GET请求到指定的URL,然后检查响应状态码以确认请求成功。如果成功,它使用BeautifulSoup解析HTML页面,并查找所有包含书籍信息的标签。之后遍历这些书籍信息,从中提取书名和作者,并打印出来。 请注意,在实际使用中,你需要根据目标网站的具体HTML结构来调整解析代码,并且确保遵守目标网站的`robots.txt`文件规定和使用条款,以免进行非法爬取
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值