requests+beautifulsoup爬取豆瓣图书

使用Xpath和BeautifulSoup来解析网页可以说真的很简便。

import requests
from bs4 import BeautifulSoup
from random import choice

url = 'https://book.douban.com/tag/%E7%BC%96%E7%A8%8B'
ua = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"
headers = {'User-Agent': ua}

with open('hosts') as f:
    proxies = [proxy.strip() for proxy in f.readlines()]

    with requests.get(url, headers, proxies={"http": choice(proxies)}) as resp:
        soup = BeautifulSoup(markup=resp.text, features='lxml')
        # //li[@class="subject-item"]//h2/a/text()
        # //li[@class="subject-item"]//span[@class="rating_nums"]/text()
        books = soup.select('.subject-item')
        # print(books)

        for book in books:
            # print(book.select('h2 a'))
            title = ''.join(map(lambda x: x.strip(), book.select('h2 a')[0].text))  # 合并副标题
            rate = book.select('.rating_nums')[0].text
            print(title, rate)

解析结果:

计算机程序的构造和解释:原书第2版 9.5
编码:隐匿在计算机软硬件背后的语言 9.2
代码大全(第2版) 9.3
深入理解计算机系统 9.5
C程序设计语言:第2版·新版 9.4
算法导论(原书第2版) 9.3
算法(第4版) 9.4
JavaScript高级程序设计(第3版) 9.3
黑客与画家:硅谷创业之父PaulGraham文集 8.8
集体智慧编程 9.0
编程珠玑:第2版 9.1
Java编程思想(第4版) 9.1
Python编程:从入门到实践:从入门到实践 9.1
C++Primer中文版(第4版) 9.2
流畅的Python 9.5
程序员的自我修养:链接、装载与库 8.8
UNIX环境高级编程:第2版 9.4
Python编程快速上手:让繁琐工作自动化 9.0
程序员修炼之道:从小工到专家 8.6
重构:改善既有代码的设计 9.0

猜你喜欢

转载自www.cnblogs.com/keithtt/p/10177262.html