python学习的第四天

爬虫(本地HTML)

  • 获取标签中的内容,末尾要添加text()
  • //表示可以代表从任意位置出发
    格式://标签1[@属性=属性值]/标签2[@属性=属性值].../text()
  • 获取标签 — //标签/text()
  • 获取属性 — //@属性
 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()')
    p = selector.xpath('//p/text()')
    print(p[0])

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

requests包

  • respnse.text—获取str类型的响应 修改编码方式response.encoding
  • respnse.content—获取bytes类型的响应 图片类型 修改编码方式
  • respnse.headers—获取响应头
  • respnse.status_code—获取状态码
  • 大多数网站存在反爬虫的编码,所以,需要使用请求头
mport requests
# 没有添加请求头的知乎网站
resp = requests.get('https://www.zhihu.com/')
print(resp.status_code)

# 使用字典定义请求头
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('https://www.zhihu.com/', headers = headers)
print(resp.status_code)

写入本地

#当当网
import  requests
def spider_dangdang(isbn):
    url='http://search.dangdang.com/?key={}&act=input'.format(isbn)
#目标站点地址
    #获取站点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)
spider_dangdang('9787115490995')

爬虫(当当网搜索)

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)
    # 获取站点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
    # 提取目标站的信息
    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')
图书价格top10

test—爬虫(豆瓣电影)

  • 电影名,上映日期,类型,上映国家,想看人数
  • 根据想看人数进行排序
  • 绘制即将上映电影国家的占比图
  • 绘制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
def spider_dangdang():
    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
    selector = html.fromstring(html_data)
    ul_list = selector.xpath('//div[@id="showing-soon"]/div')
    print('您好,共有{}部电影即将上映'.format(len(ul_list)))

    # 遍历 ul_list
    for li in ul_list:
        #  电影名称
        title = li.xpath('./div/h3/a/text()')[0]
        print(title)
        #  上映日期
        date = li.xpath('./div/ul/li[1]/text()')[0]
        print(date)
        #类型
        type =li.xpath('./div/ul/li[2]/text()')[0]
        print(type)
        #上映国家
        city=li.xpath('./div/ul/li[3]/text()')[0]
        print(city)
        #想看人数
        people=li.xpath('./div/ul/li[4]/span/text()')[0]
        print(people)
        people = int(people.replace('人想看',''))

        # 添加每一个电影的相关信息
        movie_list.append({
            'title':title,
            'date':date,
            'type':type,
            'city':city,
            'people':people
        })
    print(movie_list)
    # 按照想看人数排序进行排序
    movie_list.sort(key=lambda x:x['people'],reverse=True)

    #提取city信息
    country=[]
    for city in movie_list:
        country.append((city['city']))
    c={}
    #将国家信息汇总
    for city in country:
        c[city] = c.get(city, 0) + 1
    print(c)
    items = list(c.items())
    #分别提取国家名和次数
    baifeibi = []
    guojia = []
    for i in range(len(items)):
        city,bai = items[i]
        baifeibi.append(bai)
        guojia.append(city)
    plt.pie(baifeibi, labels=guojia, autopct='%1.1f%%')
    plt.show()

    # 最想看的电影排名 柱状图
    # 电影名
    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['people'] 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('test.csv')

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

友情链接更多精彩内容