爬蟲學習
# -*- coding: utf-8 -*-
# @Time : 2019/7/31 11:28
# @Author : Eric Lee
# @Email : li.yan_li@neusoft.com
# @File : spider_dangdang.py
# @Software: PyCharm
import requests
from lxml import html
def spider_dangdang(isbn):
# 目標站點地址
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)
XPath
XPath 節(jié)點
節(jié)點
在 XPath 中拂蝎,有七種類型的節(jié)點:元素穴墅、屬性、文本温自、命名空間玄货、處理指令、注釋以及文檔(根)節(jié)點悼泌。XML 文檔是被作為節(jié)點樹來對待的松捉。樹的根被稱為文檔節(jié)點或者根節(jié)點。
請看下面這個 XML 文檔:
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
上面的XML文檔中的節(jié)點例子:
<bookstore> (文檔節(jié)點)
<author>J K. Rowling</author> (元素節(jié)點)
lang="en" (屬性節(jié)點)
基本值(或稱原子值馆里,Atomic value)
基本值是無父或無子的節(jié)點隘世。
基本值的例子:
J K. Rowling
"en"
項目(Item)
項目是基本值或者節(jié)點。
節(jié)點關系
父(Parent)
每個元素以及屬性都有一個父鸠踪。
在下面的例子中丙者,book 元素是 title、author营密、year 以及 price 元素的父:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
子(Children)
元素節(jié)點可有零個械媒、一個或多個子。
在下面的例子中评汰,title纷捞、author、year 以及 price 元素都是 book 元素的子:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
同胞(Sibling)
擁有相同的父的節(jié)點
在下面的例子中被去,title主儡、author、year 以及 price 元素都是同胞:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
先輩(Ancestor)
某節(jié)點的父惨缆、父的父糜值,等等。
在下面的例子中踪央,title 元素的先輩是 book 元素和 bookstore 元素:
<bookstore>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
后代(Descendant)
某個節(jié)點的子臀玄,子的子,等等畅蹂。
在下面的例子中健无,bookstore 的后代是 book、title液斜、author累贤、year 以及 price 元素:
<bookstore>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
選取節(jié)點
電影top5
import requests
from lxml import html
import pandas as pd
import jieba
from matplotlib import pyplot as plt
plt.rcParams["font.sans-serif"] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def Film():
# 目標站點地址
url = 'https://movie.douban.com/cinema/later/chongqing/'
header = {"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=header)
html_data = resp.text
# 提取目標站的信息
selector = html.fromstring(html_data)
film = selector.xpath('//div[@id="showing-soon"]/div')
print(film)
div_list = []
for film_list in film:
# 電影名
title_list = film_list.xpath('./div/h3/a/text()')[0]
print(title_list)
# 上映時間
time_list = film_list.xpath('./div/ul/li[1]/text()')[0]
print(time_list)
# 電影類型
type_list = film_list.xpath('./div/ul/li[2]/text()')[0]
print(type_list)
# 上映國家
con_list = film_list.xpath('./div/ul/li[3]/text()')[0]
print(con_list)
# 想看人數(shù)
number_list = film_list.xpath('./div/ul/li[4]/span/text()')[0]
print(number_list)
# 替換
number_list = int(number_list.replace('人想看',''))
# 添加電影信息
div_list.append({
'title': title_list,
'time': time_list,
'type': type_list,
'con': con_list,
'number': number_list
})
# 按照想看人數(shù)排序
div_list.sort(key=lambda x:x['number'], reverse=True )
print(div_list)
# 遍歷
for items_list in div_list:
print(items_list)
# 繪制top5最想看的電影占比圖
# 提取前五部電影信息
top5_store = [div_list[i] for i in range(5)]
# 提取電影名
x = [x['title'] for x in top5_store]
print(x)
# 提取想看人數(shù)
y = [x['number'] for x in top5_store]
print(y)
explode = [0.1, 0, 0, 0, 0]
plt.pie(y, explode=explode, labels=x, shadow=True, autopct='%1.1f%%')
plt.axis('equal')
plt.legend(loc=2)
plt.show()
# 繪制即將上映電影國家的占比圖
counts = {}
# 提取所有上映國家
s = [x['con'] for x in div_list]
print(s)
# 統(tǒng)計上映國家與數(shù)量
for word in s:
counts[word] = counts.get(word, 0) + 1
print(counts)
# 提取上映國家
name = counts.keys()
print(name)
# 提取數(shù)量
number = counts.values()
print(number)
explode1 = [0.1, 0, 0, 0]
plt.pie(number, explode=explode1, labels=name, shadow=True, autopct='%1.1f%%')
plt.axis('equal')
plt.legend(loc=2)
plt.show()
Film()