requests库爬取当当商品信息I

requests库爬取当当商品信息(requests,lxml)

简单记录一下实习学习爬虫的内容,本次学习包括requests库爬取当当,豆瓣等网站的信息,使用jieba对爬取到到的评论的中文进行处理,使用wordcloud对爬取到的数据绘制对应的词云,还包括lxml对爬取到的网站内容进行筛选,其余部分会分次上传。

1,使用requests库向网站发起请求
使用到的库——requests,利用requests的get方法,向对应网站的服务器发起访问,从而获取到对应网站的信息,实质上就是一个模拟游览器对对应网站,发起访问的过程。

#-*-coding=utf-8-*-
#@Time: 2020/11/2 15:48
#@File : spider_dangdang.py
#@Software: PyCharm
#@Author:miko
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"}
def spider_all(url):
    response=requests.get(url,headers=headers)
    juge=response.status_code
    print(juge)
    print(response.text)

headers能够在游览器的调试器里面找到,点击f12进入调试台,进入network也就是网络窗口,然后随便点击一个文件,找到标头里面的user-agent,放到你代码里面就能解决部分网站无法获得信息的问题,requests能将你传入的headers传给对方服务器,这是一个简单的伪装(告诉别人服务器你的操作系统访问游览器的信息,对方服务器能根据你的操作系统传会指定格式的网页代码)。
如果没有显示文件,直接刷新网站,就出现文件了
在这里插入图片描述
requests.get方法获取到的访问是一个response类型,这个类有status_code的属性,能得到访问到的网站的状态码,200是访问成功,400,500,404等是访问失败,也就是你爬虫被发现了。
而返回的这个response类型中的text属性,能让你得到网页的源码,我们也就是利用这个方法去得到网页的源码,对网页源码中我们需要的信息进行筛选和处理。所以,我们会用到lxml库中的html这个包。
2,使用lxml库中的html包对获取到的网页源码进行信息筛选

lxml库相对于使用re,也就是正则表达式对网站的源码信息进行处理方便了很多,不要求会正则,只需要对网站结构熟悉就能上手。
html包中的fromstring()传入的参数就是你的源码,这个方法能能把你的源码转变为一个lxml.html.HtmlElement类型,你就可以利用这个类的xpath方法去根据网页的标签结构去获取到对应的信息
"//“代表的是从任何地方开始寻找,”@"能允许你获得标签内属性的值,"text()"能允许你获取到标签内的信息。

#
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"}
def spider_all(url):
    response=requests.get(url,headers=headers)
    print(response.status_code)
    html_code=response.text
    datas=html.fromstring(html_code)
    print(type(datas))
    data=etree.HTML(html_code)
    print(type(data))
spider_all("https://movie.douban.com/top250?start=0&filter=")

etree的HTML方也能达到fromstring的效果,创建一个lxml.etree._Element类,也能使用xpath方法去html网页代码结构中去寻找你所需要的信息。
3,解析url实现翻页功能
爬虫中往往是需要爬取多个页面的,而这个爬取多种页面的实现方式目前作者我只知道两种,一种是通过解析url,不断的改变网页url去实现翻页的功能,而我们可以观察一下当当的url

http://search.dangdang.com/?key=python%B1%E0%B3%CC%20%B4%D3%C8%EB%C3%C5%B5%BD%CA%B5%BC%F9&act=input

观察这个商品搜索页面我们就能发现,有一大堆%?&等符号,这些符号是url传参的形式进行前后端交互的表现,前端利用url,也就是你的地址,在这个地址内包含后端需要的信息,一般传参的部分是从?开始,大家可以做个参考,而观察这个url,其中的key=也就是你在搜索框内输入并提交上去的内容(大家可以多次去对页面进行各种各样的操作,去观察这个url,改里面的值,猜这些参数的意思)而这个参数的值是经过解码的,编码是url编码格式,所以这个地方就是我们的下手点,根据这个url我们能控制搜索的商品信息(是不是很神奇?)
而我们尝试翻到下一页,我们就会发现url多出了一个参数

&page_index=2

是不是感觉有点奇妙,没猜错,这个就是当前的页码。
所以这个地方也就是我们入手的地方,这样能允许我们去访问到多页的内容,去控制访问多少页,而如果想要爬完整个网页,我不知道总共多少页怎么办,那么就有一个更简便的方法了。

4,控制网页翻页,找到下一页的url链接地址
找到这个链接的位置的方式仍然是利用f12打开调试器,锁定到翻页按钮上,找到对应url爬下来,不断的更改你爬虫的url,而xpath寻找的特性是如果没找到会返回None值,而我们就可以利用这个None值进行判断,在恰当的地方终止爬虫,达到爬取全部内容的效果。

next_page=item.xpath('//div[@class="paging"]/ul[1]/li[@class="next"]/a/@href')
            if len(next_page)==0:
                url=None
            else:
                url="http://search.dangdang.com"+next_page[0]
#此处代码为当当网商品信息爬取的测试实例。
#-*-coding=utf-8-*-
#@Time: 2020/11/2 15:48
#@File : spider_dangdang.py
#@Software: PyCharm
#@Author:miko
import requests
from lxml import html
import time
import urllib
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36"}
def spider_all(url):
    response=requests.get(url,headers=headers)
    juge=response.status_code
    information=[]
    if juge==200:
        html_code=response.text
        data=html.fromstring(html_code)
        for i in range(1,61):
            product_code=data.xpath("//div[@id='search_nature_rg']/ul/li[@ddt-pit="+str(i)+"]")
            shop_nub=len(product_code)
            print(shop_nub)
            for items in product_code:
                item={}
                title=items.xpath("./p[@class='name']/a/@title")[0]
                item["title"]=title
                link=items.xpath("./p[@class='name']/a/@href")
                item["link"]=link
                price=items.xpath("./p[@class='price']/span/text()")
                item["price"]=price
                shop=items.xpath("./p[@class='search_shangjia']/a/@title")
                item["shop"]=shop
                information.append(item)
            time.sleep(0.1)
        return information
    else:print("the website is not allow you to access")

#single_one

def spider_title(url):
    response=requests.get(url,headers=headers)
    print(response.status_code) #获取到网页状态码
                                #404 未找到网页 200 可以访问 500服务器内部有问题
    html_code=response.text
    data=html.fromstring(html_code)
    title_list=[]
    for i in range(1,61):
        title=data.xpath("//div[@id='search_nature_rg']/ul/li[@ddt-pit="+str(i)+"]/p/a/@title")[0]
        title_list.append(title)
        time.sleep(0.1)
    return title_list
def spider_prise(url):
    response=requests.get(url)
    print(response.status_code) #获取到网页状态码
                                #404 未找到网页 200 可以访问 500服务器内部有问题
    html_code=response.text
    data=html.fromstring(html_code)
    price_list=[]
    for i in range(1,61):
        price=data.xpath("//div[@id='search_nature_rg']/ul/li[@ddt-pit="+str(i)+"]/p[@class='price']/span/text()")[0]
        price_list.append(price)
        time.sleep(0.1)
    return price_list
if __name__=="__main__":
    #对中文进行url的再编码
    # search_book=input().encode()
    # data=urllib.parse.quote_plus(search_book)
    # print(data)
    data=input()
    for i in range(1,2):
        title=spider_title("http://search.dangdang.com/?key=python%B1%E0%B3%CC%20%B4%D3%C8%EB%C3%C5%B5%BD%CA%B5%BC%F9&act=input&page_index="+str(i))
        print(title)
    price=spider_all("http://search.dangdang.com/?key=python%B1%E0%B3%CC%20%B4%D3%C8%EB%C3%C5%B5%BD%CA%B5%BC%F9&act=input&page_index=1")
    print(price)
    for i in range(1,2):
        items=spider_all("http://search.dangdang.com/?key=python%B1%E0%B3%CC%20%B4%D3%C8%EB%C3%C5%B5%BD%CA%B5%BC%F9&act=input&page_index="+str(i))
        print(items)

这个地方的代码是整个当当网爬虫的代码,有需要自取,其中有些地方用到的库并未在这份笔记内写出,有想要了解的请看文章最后的链接(PS:最近有点忙,接下来的代码会短短续续的上传)。

#此处是实际项目使用的爬虫代码,将爬虫写为了类,利用类的特性。
#-*-coding=utf-8-*-
#@Time: 2020/11/4 11:47
#@File : spider_dangdang.py
#@Software: PyCharm
#@Author:miko
import urllib
from selenium import webdriver
import requests
from lxml import html
import time
import jieba
import imageio
from wordcloud import WordCloud
headers={
        "Request URL": "https://movie.douban.com/cinema/later/yingkou/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36",
    }
class Spider_DD:
    def __init__(self,name):
        data=name
        self.url = f"http://search.dangdang.com/?key={data}&act=input&page_index=1"
        self.headers=headers
        self.links=[]
    def spider(self,url):
        print(url)
        response=requests.get(url)
        time.sleep(1.5)
        print(response.status_code)
        html_code=response.text
        data=html.fromstring(html_code)
        items = data.xpath('//div[@id="search_nature_rg"]/ul/li')
        print(len(items))
        information = []
        juge_lpage=None
        for item in items:
            dic = {}
            title=item.xpath('./a/@title')[0]
            dic["name"] = title
            link=item.xpath('./a/@href')[0]
            dic["link"] = link
            self.links.append(link)
            price=item.xpath('./p[@class="price"]/span[@class="search_now_price"]/text()')
            if len(price)==0:
                price=item.xpath('./div[@class="ebook_buy"]/p/span[@class="search_now_price"]/text()')[0]
                price=price.replace("¥","")
                dic["price"]=float(price)
            else:
                price = price[0].replace("¥", "")
                dic["price"]=float(price[0])

            shop = item.xpath('./p[@class="search_shangjia"]/a/text()')
            if shop == []:
                dic["shop"] = "自营"
            else:
                dic["shop"] = shop[0]
            information.append(dic)
            next_page=item.xpath('//div[@class="paging"]/ul[1]/li[@class="next"]/a/@href')
            if len(next_page)==0:
                self.url=None
            else:
                self.url="http://search.dangdang.com"+next_page[0]
        # if len(items)==60:
        #     juge_lpage = "http://search.dangdang.com" + str(data.xpath('//div[@class="paging"]/ul/li[@class="next"]/a/@href')[0])
        #     print(juge_lpage)
        #     if len(juge_lpage)==0:
        #         self.url=None
        #     else:
        #         self.url=juge_lpage
        # else:self.url=None
        return information

    def get_comments(self,com_url="http://product.dangdang.com/24003310.html"):
        url=com_url


        opt = webdriver.ChromeOptions()  # 创建浏览器
        # 阻止网页自动关闭
        # 关闭“chrome正受到自动测试软件的控制”
        # V75以及以下版本
        # option.add_argument('disable-infobars')
        # V76以及以上版本
        opt.add_experimental_option('useAutomationExtension', False)
        opt.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 不自动关闭浏览器
        opt.add_experimental_option("detach", True)

        driver = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe",
                                  options=opt)  # 创建浏览器对象
        driver.get(url)  # 打开网页
        driver.maximize_window()  # 最大化窗口
        time.sleep(3)  # 加载等待
        # #滚动到底部
        js = "return action=document.body.scrollHeight"
        height = driver.execute_script(js)
        # 将滚动条调整至页面底部
        driver.execute_script('window.scrollTo(0, document.body.scrollHeight)')

        response = requests.get(url, headers=self.headers)
        time.sleep(1)
        print(response.status_code)
        html_code = driver.page_source


        data=html.fromstring(html_code)
        nub=10
        comments = ""
        i=0
        while nub==10:
            boxs=data.xpath('//div[@id="comment_list"]/div[1]/div')
            nub=len(boxs)
            for item in boxs:
                try:
                    comments+=item.xpath('./div[1]/div[2]/span/a/text()')[0]
                except IndexError:
                    continue
            try:
                driver.find_element_by_xpath('//div[@id="comment_list"]/div[2]/div/a[last()]').click()
            except :
                break
            time.sleep(1)
            i+=1
            if i==10:
                break
        driver.quit()
        return comments


    def drawing(self,comments,i):
        data_list = jieba.lcut(comments)
        data = " ".join(data_list)
        mask = imageio.imread("./file/yuansheng.png")  # 蒙版
        cloud = WordCloud(
            background_color="pink",
            width=1200,
            height=1200,
            font_path="msyh.ttc",
            mask=mask
        )

        dic = {}
        for str in data_list:
            if 2 <= len(str) <= 3:
                if dic.get(str) != None:
                    dic[str] += 1
                else:
                    dic[str] = 1
        lists = list(dic.items())
        lists.sort(key=lambda x: x[1], reverse=True)
        print(lists)
        try:
            cloud.generate(data).to_file(f"./file/img/draw{i.strip()}.png")
        except:
            pass
            #这里之后还得进行优化,处理重名,多数据的情况



    def run(self):
        datas=[]
        i=0
        while self.url!=None:
            print("success")
            datas.extend(self.spider(self.url))
            if i ==10:
                break
            i+=1
        datas.sort(key=lambda x:x["price"])
        # for i in datas:
        #     comments=self.get_comments(i["link"])
        #     self.drawing(comments,i["name"])
        #     print("success")
        return datas
if __name__ == '__main__':
    search_book = "python"
    data=Spider_DD(search_book)
    datas=data.run()
    print(datas)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值