爬虫项目实战十一:爬取当当网商品信息

目标

批量爬取当当网商品信息,保存为csv文件到本地。

项目准备

软件:Pycharm
第三方库:requests,fake_useragent,lxml,csv
网站地址:http://search.dangdang.com/

网站分析

打开网站页面,去搜索一种商品,比如豆豆鞋。
在这里插入图片描述
可以看到:

http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input

key=商品名称
分析一下是否为静态网页。
F12打开开发者模式。
复制关键字,Ctrl+U查看源代码。粘贴过来,发现可以找到。
在这里插入图片描述
静态网页。

页码分析

http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input&page_index=1
http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input&page_index=2
http://search.dangdang.com/?key=%B6%B9%B6%B9%D0%AC&act=input&page_index=3

发现page_index之后会变化。

反爬分析

同一个ip地址去多次访问会面临被封掉的风险,这里采用fake_useragent,产生随机的User-Agent请求头进行访问。

代码实现

1.导入相对应的第三方库,定义一个class类继承object,定义init方法继承self,主函数main继承self。

import requests
from fake_useragent import UserAgent
from lxml import etree
import csv
class dangdang(object):
    def __init__(self):
        self.url = 'http://search.dangdang.com/?key={}&page_index={}'
        ua = UserAgent(verify_ssl=False)
        for i in range(1, 100):
            self.headers = {
    
    
                'User-Agent': ua.random
            }
    def main(self):
    	pass
if __name__ == '__main__':
    spider = dangdang()
    spider.main()

2.发送请求,获取网页。

    def get_html(self,url):
        response=requests.get(url,headers=self.headers)
        html=response.text
        return html

3.解析网页获取商品信息并保存到本地。

    def parse_html(self,html):
        target=etree.HTML(html)
        titles=target.xpath('//p[@class="name"]/a/@title')
        prices=target.xpath('//p[@class="price"]/span/text()')
        links=target.xpath('//p[@class="name"]/a/@href')
        with open('F:/pycharm文件/document/dangdang.csv','a',newline='',encoding='gb18030') as f:
            csvwriter = csv.writer(f, delimiter=',')
            for title,price,link in zip(titles,prices,links):
                csvwriter.writerow([title,price,link])

4.主函数及函数调用。

    def main(self):
        product = str(input('请输入您要浏览的商品:'))
        end_page=int(input("要爬多少页:"))
        for page in range(1,end_page+1):
            url = self.url.format(product,page)
            print("第%s页。。。。"%page)
            html=self.get_html(url)
            self.parse_html(html)
            print("第%s页爬取完成" % page)

效果显示

在这里插入图片描述
打开本地文件。
在这里插入图片描述
完整代码如下:

import requests
from fake_useragent import UserAgent
from lxml import etree
import csv
class dangdang(object):
    def __init__(self):
        self.url = 'http://search.dangdang.com/?key={}&page_index={}'
        ua = UserAgent(verify_ssl=False)
        for i in range(1, 100):
            self.headers = {
    
    
                'User-Agent': ua.random
            }
    def get_html(self,url):
        response=requests.get(url,headers=self.headers)
        html=response.text
        return html
    def parse_html(self,html):
        target=etree.HTML(html)
        titles=target.xpath('//p[@class="name"]/a/@title')
        prices=target.xpath('//p[@class="price"]/span/text()')
        links=target.xpath('//p[@class="name"]/a/@href')
        with open('F:/pycharm文件/document/dangdang.csv','a',newline='',encoding='gb18030') as f:
            csvwriter = csv.writer(f, delimiter=',')
            for title,price,link in zip(titles,prices,links):
                csvwriter.writerow([title,price,link])
    def main(self):
        product = str(input('请输入您要浏览的商品:'))
        end_page=int(input("要爬多少页:"))
        for page in range(1,end_page+1):
            url = self.url.format(product,page)
            print("第%s页。。。。"%page)
            html=self.get_html(url)
            self.parse_html(html)
            print("第%s页爬取完成" % page)
if __name__ == '__main__':
    spider = dangdang()
    spider.main()

声明:仅做自己学习参考使用。

猜你喜欢

转载自blog.csdn.net/qq_44862120/article/details/107889276