Python爬虫学习-新华书店书本数据定向爬虫(实例)

在学习了半个月python基础知识以及相关的爬虫基础技术后,尝试学以致用,本次决定使用requests、BeautifulSoup来对新华书店(https://www.xhsd.com小说类书本商品信息进行爬取。

1. 爬虫的构建思路进行分析:

将代码分为4块;

  • 第一块构建函数getHTMLText(),该函数的作用是通过requests来获取到页面的信息;
  • 第二块构建fillList(),该函数是利用BeautifulSoup来提取出我们需要的信息;
  • 第三块构建函数printList(),该函数是将信息进行打印;
  • 第四块就是主函数,对上面三个方法进行合理使用。

2. 爬虫代码的编写

首先,我们先写好整体的框架:

第一步,导包

import requests
import bs4

第二步,创建函数

def getHTMLText():
	pass
def fillList(demo):
	pass
def printList(fllist):
	pass
if __name__ == '__main__':
	pass

第三步,补充相关函数
对getHTMLText()进行构建:

def getHTMLText(url1):
#获取网页地址url1
    try:
    #使用try来抛出错误,避免程序异常导致停止
        kv = {'user-agent': 'Mozilla/4.0'}
        #设置浏览器的类型,进行迷惑
        r=requests.get(url1,headers=kv)
        r.raise_for_status()
        #通过.raise_for_status()来抛出连接异常
        r.encoding=r.apparent_encoding
        #设置字符编码
        demo=r.text
        return demo
        #返回页面所有的信息demo
    except:
        print("爬取失败")

对fillList(demo)进行构建:

def fillList(demo):
	soup = BeautifulSoup(demo, 'html.parser')
	#对获取到的页面信息进行html解析
    for li in soup.find('ul',class_='shop-search-items-img-type').children:
    #对书本信息放置的li标签进行ul的下行遍历,soup.find('ul',class_='shop-search-items-img-type')用来找到所需要的ul
    	from bs4 import BeautifulSoup
        if isinstance(li,bs4.element.Tag):
        #使用bs4中的isinstance()方法来排除类型不符的li标签
           	name=li('a')
           	#获取书名
            author=li('span')
         	#author变量对应的span标签中有两个信息,第一个是作者author[0],第二个是书本价格author[1]
            if author[0].string == None: author[0].string = '空'
            if author[1].string == None: author[1].string = '空'
            if name[1].string == None: name[1].string = '空'
            #判断当其中的信息为空时,对其进行赋值,避免后期的打印出现的错误
            fllist.append([name[1].string,author[0].string,author[1].string])
            #将每本书的书本信息以整体的方式添加到fllist列表中。

对printList(fllist):进行构建:

def printList(fllist):
    tplt2 = "{0:^3}\t{1:^2}\t{2:{4}^30}\t{3:^4}"
    for i in range(len(fllist)):
        #使用循环来打印出书本信息
        u=fllist[i]
        print(tplt2.format((i+1),u[0],u[1], u[2],chr(12288)))
        #使用chr(12288)来避免字符中的空格排列混乱

最后编写主函数

if __name__ == '__main__':
    tplt = "{0:^3}\t{1:^10}\t{2:{4}^12}\t{3:^10}"
    print(tplt.format("编号","书名",'作者','价格',chr(12288)))
    url = "https://search.xhsd.com/search?frontCategoryId=33"
    #目的网址
    fllist=[]
    #定义fllist函数来封装信息
    try:
        for i in range(20):#7208
        #共7208页,对书本信息页面前20页爬取进行验证代码准确性
            bat="&pageNo="+(i+1).__str__()
            #页数设定
            url1=url+bat
            demo=getHTMLText(url1)
            fillList(demo)
        printList(fllist)
        #打印出信息
    except:
        print('爬取失败')

3. 运行结果图

在这里插入图片描述
在这里插入图片描述详细数据如下
https://download.csdn.net/download/bri0117/10961352
在打印的文字排版上还有些问题有待修改。

4. 源码

import re
import requests
from bs4 import BeautifulSoup
import bs4
# box=input("请输入要统计的物品信息关键字:")
def getHTMLText(url1):
    try:
        kv = {'user-agent': 'Mozilla/4.0'}
        r=requests.get(url1,headers=kv)
        #设置浏览器的类型,进行迷惑
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        print("爬取失败")
def fillList(demo):
    soup = BeautifulSoup(demo, 'html.parser')
    for li in soup.find('ul',class_='shop-search-items-img-type').children:
        if isinstance(li,bs4.element.Tag):
            author=li('span')
            name=li('a')
            if author[0].string == None: author[0].string = '空'
            if author[1].string == None: author[1].string = '空'
            if name[1].string == None: name[1].string = '空'
            fllist.append([name[1].string,author[0].string,author[1].string])
def printList(fllist):
    tplt2 = "{0:^3}\t{1:^2}\t{2:{4}^30}\t{3:^4}"
    for i in range(len(fllist)):
        u=fllist[i]
        print(tplt2.format((i+1),u[0],u[1], u[2],chr(12288)))
if __name__ == '__main__':
    tplt = "{0:^3}\t{1:^10}\t{2:{4}^12}\t{3:^10}"
    print(tplt.format("编号","书名",'作者','价格',chr(12288)))
    url = "https://search.xhsd.com/search?frontCategoryId=33"
    fllist=[]
    try:
        for i in range(20):#7208
            bat="&pageNo="+(i+1).__str__()
            url1=url+bat
            demo=getHTMLText(url1)
            fillList(demo)
        printList(fllist)
    except:
        print('爬取失败')

用文件保存数据源码:

import re
import requests
from bs4 import BeautifulSoup
import bs4
import os
# box=input("请输入要统计的物品信息关键字:")
def getHTMLText(url1):
    try:
        kv = {'user-agent': 'Mozilla/4.0'}
        r=requests.get(url1,headers=kv)
        #设置浏览器的类型,进行迷惑
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        print("爬取失败")
def fillList(demo):
    soup = BeautifulSoup(demo, 'html.parser')
    for li in soup.find('ul',class_='shop-search-items-img-type').children:
        if isinstance(li,bs4.element.Tag):
            author=li('span')
            name=li('a')
            if author[0].string == None: author[0].string = '空'
            if author[1].string == None: author[1].string = '空'
            if name[1].string == None: name[1].string = '空'
            fllist.append([name[1].string,author[0].string,author[1].string])
# def printList(fllist):
#     tplt2 = "{0:^3}\t{1:^2}\t{2:{4}^30}\t{3:^4}"
#     for i in range(len(fllist)):
#         u=fllist[i]
#         print(tplt2.format((i+1),u[0],u[1], u[2],chr(12288)))
#将图书信息放入txt文本中
def PrintFllist(fllist):
    root = "D://pythontest//testtxt//"
    path =root+"新华书店小说类图书信息表.txt"
    try:
        if not os.path.exists(root):
            os.mkdir(root)
        if not os.path.exists(path):
            with open(path,"w") as f:
                tplt = "{0:^2}\t{1:^1}\t{2:{4}^2}\t{3:^2}"
                tplt2 = "\n{0:^3}\t{1:^1}\t{2:{4}^2}\t{3:^2}"
                f.write(tplt.format("编号", '价格', '作者', "书名", chr(12288)))
                #取前20页
                for i in range(len(fllist)):
                    u=fllist[i]
                    f.write(tplt2.format((i+1),u[2],u[1], u[0],chr(12288)))
            print('爬取成功')
        else:
            print('文件已存在')
    except:
        print('爬取失败')
if __name__ == '__main__':
    # tplt = "{0:^3}\t{1:^10}\t{2:{4}^12}\t{3:^10}"
    # print(tplt.format("编号","书名",'作者','价格',chr(12288)))
    url = "https://search.xhsd.com/search?frontCategoryId=33"
    fllist=[]
    try:
        for i in range(7208):#7208
            bat="&pageNo="+(i+1).__str__()
            url1=url+bat
            demo=getHTMLText(url1)
            fillList(demo)
        PrintFllist(fllist)
    except:
        print('爬取失败')

纯手写,需要转载须事先声明我

猜你喜欢

转载自blog.csdn.net/Bri0117/article/details/86775742