python 爬虫 爬取当当网图书信息

初次系统的学习python,在学习完基本语法后,对爬虫进行学习,现在对当当网进行爬取,爬取了基本图书信息,包括图书名、作者等
import requests
from time import sleep
from lxml import etree
class dangdang_spider():
#定义爬虫类
    def __init__(self):
        self.url="http://category.dangdang.com/pg{}-cp01.00.00.00.00.00.html" #爬虫网址
        self.headers= {#设置headers
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
#爬取基本网页信息
    def parse(self,url):
         r=requests.get(url,headers=self.headers)
         return r.content.decode(encoding='gbk')
#对数据处理
    def handle_data(self, data,i):
        html = etree.HTML(data)#对信息进行html格式化
        msg_list=[]
        li_list=html.xpath("// ul[ @ id = 'component_0__0__6612']/li")#利用xpath锁定图书信息所在的html标签
        for li in li_list:
            msg = {}
            msg['book_title'] = li.xpath('./p/a/text()')[0]
            msg['book-author'] = li.xpath('./p/span[1]/a[1]/@title')[0]if len(li.xpath('./p/span[1]/a[1]/@title')) >0 else '无'
            msg['book-publish'] = li.xpath('./p/span[3]/a/text()')[0]if len(li.xpath('./p/span[3]/a/text()')) >0 else '无'
            msg['book-publish_time'] = li.xpath('./p[5]/span[2]/text()')[0].replace(' /','')if len(li.xpath('./p[5]/span[2]/text()')) >0 else '无'
            msg['book-descrip'] = li.xpath('./p[2]/text()')[0]if len(li.xpath('./p[2]/text()')) >0 else '无'
            msg['book-price'] = li.xpath('./p[3]/span[1]/text()')[0]
            msg['book-pinglun'] = li.xpath('./p[4]/a/text()')[0]
            msg_list.append(msg)
        # print(msg_list)

        next_url = self.url.format(i) #构建下一页url
        return msg_list, next_url
    def save_data(self,data):
        for msg in data:
            msg_str=msg['book_title']+','+msg['book-author']+','+msg['book-publish']+','+msg['book-publish_time']+','+msg['book-descrip']+','+msg['book-price']+','+msg['book-pinglun']
            print(msg_str)
            with open('dangdang.csv','a',encoding='utf-8') as f: #写入文件
                f.write(msg_str)
                f.write('\n')
    def run(self):
        i=1
        next_url=self.url.format(i)
        while next_url:
            html_str=self.parse(next_url)
            i = i + 1
            msg_list, next_url=self.handle_data(html_str,i)
            self.save_data(msg_list)
            print(next_url)
            sleep(2)

if __name__ == '__main__':
    d=dangdang_spider()
    d.run()

爬取结果截图 爬取结果截图

                
  • 9
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
可以使用Python编程语言来爬取并下载当当网某一本书的网页内容,并保存为html格式。 具体步骤如下: 1. 导入所需的库,如requests、beautifulsoup4等。 2. 构造请求头,模拟浏览器访问。 3. 发送请求,获取网页内容。 4. 使用beautifulsoup4库解析网页内容,提取需要的信息。 5. 将提取的信息保存为html格式的文件。 下面是一个简单的Python代码示例: ```python import requests from bs4 import BeautifulSoup # 构造请求头 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'} # 发送请求,获取网页内容 url = 'http://product.dangdang.com/23384958.html' response = requests.get(url, headers=headers) html = response.text # 使用beautifulsoup4库解析网页内容,提取需要的信息 soup = BeautifulSoup(html, 'html.parser') book_title = soup.find('div', class_='name_info').h1.text.strip() book_author = soup.find('div', class_='author').a.text.strip() book_price = soup.find('span', class_='price_n').text.strip() # 将提取的信息保存为html格式的文件 with open('book.html', 'w', encoding='utf-8') as f: f.write(f'<html><head><title>{book_title}</title></head><body>') f.write(f'<h1>{book_title}</h1>') f.write(f'<p>作者:{book_author}</p>') f.write(f'<p>价格:{book_price}</p>') f.write('</body></html>') ``` 运行以上代码后,会在当前目录下生成一个名为book.html的文件,其中包含了所爬取书籍信息
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值