Python学习的第四天

一、提取网页中数据

#爬虫
#大数据
#提取本地html文件
#使用xpath语法进行提取
#使用lxml中的xpath
#使用lxml提取h1中的内容
from lxml import html #若报错找不到指定的模块,就卸载掉然后再安装
#提取html文件
with open('./index.html','r',encoding='utf-8') as f:
    html_data=f.read()
    #print(html_data)
    #解析HTML文件,获取selector对象
    selector=html.fromstring(html_data)
    #selector中调用xpath方法
    #要获取标签中的内容,末尾要加text()
    h1=selector.xpath('/html/body/h1/text()')
    print(h1[0])

    #//可以代表任意位置出发
    #//标签1[@属性=属'性值]/标签2[@属性=属性值]container
    a=selector.xpath('//div[@class="container"]/a/text()')
    print(a[0])
    p=selector.xpath('//div[@class="container"]/p/text()')
    print(p[0])

    #获取属性值
    link=selector.xpath('//div[@id="container"]/a/@href')
    print(link[0])

二、获取响应

#导入
import requests
url='https://www.baidu.com'
response=requests.get(url)
print(response)
#获取str类型的响应
#response常用
print(response.text)
#获取bytes类型的响应,下载图片用到
print(response.content)
#获取响应头,
print(response.headers)
#获取状态码:200 404 500
print(response.status_code)
#获取编码
print(response.encoding)

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>王者荣耀</title>
</head>
<body>

<h1>欢迎来到王者荣耀</h1>
<ul>
    <li><a href="https://pvp.qq.com/web201605/herodetail/508.shtml" ><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/508/508.jpg"> 伽罗</a></li>
    <li><a href="https://pvp.qq.com/web201605/herodetail/174.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/174/174.jpg"> 虞姬</a> </li>
    <li><a href="https://pvp.qq.com/web201605/herodetail/135.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/135/135.jpg" > 项羽</a></li>
    <li><a href="https://pvp.qq.com/web201605/herodetail/109.shtml"><img src="https://game.gtimg.cn/images/yxzj/img201606/heroimg/109/109.jpg"> 妲己</a> </li>

</ul>
<ol>
    <li>坦克</li>
    <li>法师</li>
    <li>射手</li>
    <li>刺客</li>
</ol>
<div>这是div标签</div>
<div class="container">
    <p>被动:伽罗的普工与技能伤害将会有限对于表的护盾效果造成一次等额伤害</p>
    <a href="https://www.baidu.com">点击跳转</a>
</div>
<div>这是第二个div标签</div>
</body>
</html>

三、对当当网爬虫数据

import requests
from lxml import html
import pandas as pd
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def spider_dangdang(isbn):
    booklist=[]
    #目标站点地址
    url='http://search.dangdang.com/?key={}&act=input'.format(isbn)
    #print(url)
    #获取站点str类型的响应
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}

    resp=requests.get(url,headers=headers)
    html_data=resp.text
    #将html页面写入本地
    # with open('./dangdang.html','w',encoding='utf-8') as f:
    #     f.write(html_data)

    #提取目标站点的信息
    selector=html.fromstring(html_data)
    ul_list=selector.xpath('//div[@id="search_nature_rg"]/ul/li')
    print('您好,共有{}家店铺售卖此图书'.format(len(ul_list)))
    #遍历ul_list
    for li in ul_list:
        #图书名称
        title=li.xpath('./a/@title')[0].strip()
        print(title)
        # 图书购买链接
        link = li.xpath('a/@href')[0]
        print(link)
        #图书价格
        price=li.xpath('./p[@class="price"]/span[@class="search_now_price"]/text()')[0]
        price=float(price.replace('¥',''))
        print(price)

        #图书卖家名称
        store=li.xpath('./p[@class="search_shangjia"]/a/text()')
        if len(store)==0:
            store='当当自营'
        else:
            store=store[0]
        #store ='当当自营' if len(store)==0 else store[0]
        print(store)

        #添加每一个商家信息
        booklist.append({
            'title':title,
            'price':price,
            'link':link,
            'store':store
        })
        #按照价格进行排序
    booklist.sort(key=lambda x:x['price'],reverse=True)
        #遍历booklist
    for book in booklist:
        print(book)
        #展示价格最低的前10家  柱状图
        #店铺名称
    top10_store=[booklist[i] for i in range(10)]
        # x=[]
        # for store in top10_store:
        #     x.append(store['store'])
    x=[x['store'] for x in top10_store]
    print(x)
        #图书的价格
    y=[x['price'] for x in top10_store]
    print(y)
    plt.barh(x,y)
    plt.show()
        #存储为CSV文件
    df=pd.DataFrame(booklist)
    df.to_csv('dangdang.csv')
spider_dangdang('9787115428028')

四、练习:对豆瓣网爬虫

#练习:https://movie.douban.com/cinema/later/chongqing/
#电影名,上映日期,类型,上映国家,想看人数
#根据想看人数进行排序
#绘制即将上映电影国家的占比图
#绘制top5最想看的电影

#请求远程端站点
import requests
from lxml import  html
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

counts={}
# 目标站点地址
def spider_douban():
    movie_list=[]
    url = 'https://movie.douban.com/cinema/later/chongqing/'
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36"}
    resp = requests.get(url, headers=headers)
    html_data = resp.text

#  将html页面写入本地
#     with open('dangdang.html', 'w', encoding='utf-8') as f:
#         f.write(html_data)
    #提取目标站信息
    selector = html.fromstring(html_data)
    ul_list = selector.xpath('//div[@id="showing-soon"]/div/div')
    print('您好,共有{}部电影即将在重庆上映'.format(len(ul_list)))

    # 遍历ul_list
    for li in ul_list:
        # 电影名称
        title = li.xpath('./h3/a/text()')[0].strip()
        print(title)
        # 上映日期
        date = li.xpath('./ul/li/text()')[0]
        print(date)
        # 类型
        type = li.xpath('./ul/li/text()')[1]
        print(type)

        # 上映国家
        country = li.xpath('./ul/li/text()')[2]
        print(country)
        # 想看人数
        num = li.xpath('./ul/li/span/text()')[0]
        print(num)
        num = int(num.replace('人想看', ''))

        #添加电影信息
        movie_list.append({
            'title':title,
            'date': date,
            'type':type,
            'country':country,
            'num':num
        })

    #按照人数进行排序
    movie_list.sort(key=lambda x:x['num'],reverse=True)

    #遍历booklist
    for movie in movie_list:
        print(movie)

    #画饼图,把国家提取出来
    city=[]
    # 提取国家信息
    for country in movie_list:
        city.append((country['country']))

    # 将国家信息汇总
    for country in city:
        if len(country) <= 1:
            continue
        else:
            counts[country] = counts.get(country, 0) + 1
    items = list(counts.items())
    print(items)

    movie_name=[]
    people=[]
    for i in range(4):
        role, count = items[i]
        print(role, count)
        movie_name.append(role)
        people.append(count)


     #绘制即将上映电影国家的占比图,饼图

    explode = [0.1, 0, 0, 0]
    plt.pie(people, explode=explode,labels=movie_name, shadow=True, autopct='%1.1f%%')
    plt.axis('equal')  # 保证饼状图是正圆,否则会有点扁
    plt.show()


    # 展示最想看的前5家,柱状图
    # 电影名称
    top5_movie = [movie_list[i] for i in range(5)]
    print(top5_movie)
    x = [x['title'] for x in top5_movie]
    print(x)
    # 想看人数
    y = [x['num'] for x in top5_movie]
    print(y)

    plt.bar(x,y)
    #plt.barh(x,y)
    plt.show()
    存储成csv文件
    df = pd.DataFrame(movie_list)
    df.to_csv('douban.csv')

spider_douban()
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 爬虫 爬虫(又被称为网页蜘蛛,网络机器人),它是一种按照一定的规则,自动地抓取互联网信息的程序或者脚本。也即它是一...
    小頴子阅读 1,594评论 0 0
  • 1.爬虫基础 1.1获取网址 url='https://www.baidu.com'response=reques...
    神坑少女7阅读 1,423评论 0 0
  • 一、爬虫 爬虫(又被称为网页蜘蛛,网络机器人),它是一种按照一定的规则,自动地抓取互联网信息的程序或者脚本。也即它...
    喵青禾阅读 2,972评论 0 0
  • 1、爬虫一些知识 (1)节点选择语法 XPath使用路径表达式来选取XML文档中的节点或者节点集。这些路径表达式和...
    小乌龟快点跑吖阅读 2,713评论 0 0
  • 用脑学习知识,知识学习越多,技能提升的概率越大。当知识和技能都在不断提升的时时候,人会更用心去学习。把知识学以致用...
    FineYoGa瑜伽仙仙阅读 1,351评论 0 0

友情链接更多精彩内容