Python学习的第四天

爬虫

提取本地html中的数据

1、新建html文件
2、读取
3、使用xpath语法进行提取
4、使用 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[@属性=属性值].../text()
    a = selector.xpath('//div[@id="container"]/a/text()')
    print(a[0])
    #获取p标签的内容
    p = selector.xpath('//div[@id="container"]/p/text()')
    print(p[0])
    #获取a标签中href中的值
    link = selector.xpath('//div[@id="container"]/a/@href')
    print(link[0])
运行结果:
读取本地xml文件

requests

1、导入

import requests

2、使用

url = 'https://www.baidu.com'
#url = 'https://www.taobao.com'
response = requests.get(url)
print(response)
#获取str类型的响应
print(response.text)
#获取bytes类型的响应
print(response.content)
#获取响应头
print(response.headers)
#获取状态码
print(response.status_code)
print(response.encoding)

3、没有添加请求头的知乎网站

resp = requests.get('https://www.zhihu.com')
print(resp.status_code)

4、使用字典定义请求头

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('http://www.zhihu.com',headers=headers)
print(resp.status_code)

爬当当网

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):
    book_list = []
    # 目标站点地址
    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)
        # 添加每一个商家的图书信息
        book_list.append({
            'title':title,
            'price':price,
            'link':link,
            'store':store
        })
    # 按照价格进行排序
    book_list.sort(key=lambda x:x['price'])

    # 遍历booklist
    for book in book_list:
        print(book)
    # 展示价格最低的前10家 柱状图
    # 店铺的名称
    top10_store = [book_list[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.bar(x, y)
    plt.barh(x, y)
    plt.show()
    # # 存储成csv文件
    df = pd.DataFrame(book_list)
    df.to_csv('dangdang.csv')

spider_dangdang('9787115428028')
运行结果:
爬当当网结果1

爬当当网结果2

价格最低TOP10

爬重庆-影讯

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
people_list = []
counts = []
# 目标站点地址
url = 'https://movie.douban.com/cinema/later/chongqing/'
#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="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)
    #  想看人数
    people = li.xpath('./ul/li/span/text()')[0]
    people = int(people.replace('人想看', ''))
    #print(people)
    people_list.append({
        'title' : title,
        'date' : date,
        'type' : type,
        'country' : country,
        'people' : people
    })
    counts.append(country)
# 按照想看人数进行排序
people_list.sort(key=lambda x:x['people'],reverse=True)
# 遍历people_list
for num in people_list:
    print(num)
# 展示价格最低的前10家 柱状图
# 店铺的名称
top5 = [people_list[i] for i in range(5)]
# # x = []
# # for store in top10_store:
# #     x.append(store['store'])
x = [x['title'] for x in top5]
print(x)
# # 图书的价格
y = [x['people'] for x in top5]
print(y)
# # plt.bar(x, y)
plt.barh(x, y)
plt.show()
# # 存储成csv文件
# df = pd.DataFrame(people_list)
# df.to_csv('douban.csv')

#绘制即将上映电影国家的占比图
china = 0
japan = 0
russia = 0
hongkong = 0
for i in range(22):
    if counts[i] == '中国大陆':
        china += 1
    elif counts[i] == '俄罗斯':
        russia += 1
    elif counts[i] == '日本':
        japan += 1
    elif counts[i] == '香港':
        hongkong += 1
count = [china,japan,russia,hongkong]
role = ['中国大陆','俄罗斯','日本','香港']
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.pie(count,shadow=True,labels=role,autopct='%1.1f%%')
plt.legend(loc=2)
plt.axis('equal')
plt.show()
运行结果:
爬重庆-影讯结果1

爬重庆-影讯结果2

想看人数最高TOP5

电影国家占比
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 爬虫——大数据 1. 提取本地HTML中的数据 1. 新建index.html文件 2. 读取HTML文件 需要安...
    婉儿吖阅读 361评论 0 0
  • 1、爬虫一些知识 (1)节点选择语法 XPath使用路径表达式来选取XML文档中的节点或者节点集。这些路径表达式和...
    小乌龟快点跑吖阅读 348评论 0 0
  • 爬虫 爬虫(又被称为网页蜘蛛,网络机器人),它是一种按照一定的规则,自动地抓取互联网信息的程序或者脚本。也即它是一...
    小頴子阅读 213评论 0 0
  • 一、爬虫 爬虫(又被称为网页蜘蛛,网络机器人),它是一种按照一定的规则,自动地抓取互联网信息的程序或者脚本。也即它...
    喵青禾阅读 380评论 0 0
  • 大把大把的产品像是柴火,把产品经理这个角色烧得火热。 满大街都是想做产品经理的人、觉得自己适合做产品经理的人、以及...
    闫淳墨阅读 358评论 0 4