zoukankan      html  css  js  c++  java
  • 【Python】从0开始写爬虫——扒狗东先流产了

    上回写到一半临时有事,竟然没有保存到!!!。这几天也是因为家人过来玩。。我也不知道写到哪儿了。我发现狗东这个奸贼很多数据是请求请求再请求,然后才拿到我们看到的数据显示上去的。我尝试了一下找齐这个数据确实有点头疼(我有查到可以用一个东西模拟浏览器去得到我们最终的页面,但是本着练习为主的思想,先不搞这么无脑的东西)。

    所以我们暂时先战略性放弃扒狗东。容我再找个好扒一点网站。下面是现在的代码。

    这里给出一个BeautifulSoup的文档链接,是中文的,很好懂: BeautifulSoup中文文档

    emmmm我们先上京东找个好看的模特:  恋裳蒂莎2018夏季夜场小女人性感后开叉包臀连衣裙紧身诱人主播超短裙 黑色 S

    根据我现在的代码,我应该是封装了一下之前的代码,然后已经爬了商品的id、名称和类目。

    目录。我不太懂规范的python项目是什么样的。我是在test目录下中测试一些第三方库的api

    app.py

    import urllib.request
    from bs4 import BeautifulSoup
    
    header = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
    }
    
    
    # 因为有时候得到的是一段 json 或者别的数据,有时候是html,所以我们单纯地先获取数据
    def get_data(url, headers=header, charset="utf-8"):
        req = urllib.request.Request(url=url, headers=headers)
        rep = urllib.request.urlopen(req)
        data = rep.read()
        return data.decode(encoding=charset)
    
    
    # 如果是个html我们就可以用BeautifulSoup解析
    def get_soup(url, headers=header, charset="utf-8"):
        data = get_data(url=url, headers=headers, charset=charset)
        return BeautifulSoup(data, "html.parser")

    jd.py

    from scrapy import app
    import re
    
    
    header = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
        # 'Referer': 'https://item.jd.com/10671563387.html'
    
    }
    
    url = "https://item.jd.com/27934623028.html"
    soup = app.get_soup(url, header, "gbk")   # 获取BeautifulSoup对象
    
    pid = re.search("[0-9]+", url).group()    # 用正则筛选id
    print("商品id:", pid)
    
    title = soup.find("div", class_="sku-name").string.strip()   # 爬商品名称
    print("商品名称:", title)
    
    page_config = soup.find("script", {"charset": "gbk"}).string
    cat = re.search("(?<=cat:s[)[,0-9]*(?=])", page_config).group()   # 用正则匹配到商品类目
    print("category: ", cat)

    控制台输出。说明是可以爬到这些的

    欢迎访问我的个人博客站点: https://yeyeck.com
  • 相关阅读:
    数据结构进阶——线段树
    基本数据结构—Hash哈希
    NOIP2013提高组 day2 2019.7.15
    基本算法——归并排序
    基本数据结构—Trie
    NOIP 2011 提高组 Day2 校模拟 7.11
    Noip2014提高组真题Day1,2 校模拟7.7
    NOIP2015 提高组 day1 7.8校模拟
    NOIP2008 提高组 6.9校模拟
    STL-#include<set>
  • 原文地址:https://www.cnblogs.com/yeyeck/p/9439061.html
Copyright © 2011-2022 走看看