當當網爬蟲
利用python的requests 庫和lxml庫,來爬取當當網的圖書信息,包括圖書名稱,圖書購買頁面url和圖書價格,本次以爬取python書籍為例
1、確定url地址
進入當當網,搜索python書籍,得到如下
所以可以知道,當你搜索書籍時,書籍的名字會放在key的后面
2、獲取地址后,就發送請求獲取數據,再返回element對象
3、在Chrome上進行元素檢查
發現每本書都在一個li下,每本書的節點是一個 a 標簽,a 標簽具有 title,href,price三個屬性,這三者分別對應書名、書的鏈接頁面和書的價格,得到了解析規則,就可以寫代碼了,注意,因為發現有些書是電子書,電子書的class="ebook_buy",而還有一些書籍是根本沒有價格的,所以要進行判斷,否則會報錯
### 4、爬取下一頁的內容
對下一頁的按鈕進行元素檢查
從上面的圖片中,我們發現 URL 地址的差異就在於 page_index 的值,所以 URL 地址最終為 http://search.dangdang.com/?key=python&act=input&&page_index=
。而 page_index 的值,我們可以通過循環依次在地址后面添加,然后進行拼接
5、保存爬下來的信息
將爬下來的東西進行放在book.txt文件下
結果:
完整代碼
import requests
from lxml import html
name = input('請輸入要搜索的圖書信息:')
# 1.准備url
url = 'http://search.dangdang.com/?key={}&act=input'.format(name)
start = 1
while True:
print('正爬取第' + str(start) + '頁信息')
start += 1
# 2.發送請求獲取數據
response = requests.get(url)
# 3.獲取html字符串
strs = response.text
# 4.獲取element對象
element = html.fromstring(strs)
# 5.先獲取分類
li_list = element.xpath('//div[@id="search_nature_rg"]/ul/li')
# 6.再獲取數據
for li in li_list:
book_name = li.xpath("./a/@title")[0]
book_link = li.xpath("./a/@href")[0]
book_price = li.xpath('./p[@class="price"]/span[@class="search_now_price"]/text()')
if not book_price:
book_price = li.xpath('./div[@class="ebook_buy"]/p[@class="price e_price"]//text()')
if not book_price:
book_price = ['沒有價格']
with open('book.txt', 'a', encoding='utf8') as f:
f.write(book_name.strip() + "\n" + book_link + "\n" + book_price[0] + "\n\n")
try:
# 爬取下一頁
a_url = element.xpath('//li[@class="next"]/a/@href')[0]
url = 'http://search.dangdang.com' + a_url
except:
print('完成,共爬取了' + str(start - 1) + '頁,請在book.txt中查看')
break