利用CSS选择器爬取豆瓣上的图书

本文介绍了如何利用requests和BeautifulSoup库通过CSS选择器爬取豆瓣网站上的图书信息,包括书名、作者、出版社和出版时间。具体展示了爬取到的多本图书详情。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用CSS选择器爬取豆瓣上的图书


主要技术:熟练掌握requests、BeautifulSoup
爬取图书链接 "https://book.douban.com/latest?icn=index-latestbook-all"

代码块

import requests
from bs4 import BeautifulSoup



def get_film(url):
    headers = {
  
  'User-Agent': 'Mozilla/5.0'}   #防止反爬虫
    try:
        r=requests.get(url,headers=headers)
        r.raise_for_status()
        r.encoding=r.status_code
        return r.text

    except:
        return "爬取失败!"

def parse_html(html,List):
    film_name1=[]
    film_actor1=[]
    film_actor2=[]
    soup=BeautifulSoup(html,'html.parser')
    for name in soup.select(
### 如何使用 CSS 解析器爬取豆瓣读书数据 为了实现这一目标,可以采用 Python 的 `requests` 库来获取网页内容,并利用 `BeautifulSoup` 结合 CSS 选择器来进行页面解析。需要注意的是,由于现代网站如豆瓣可能通过 JavaScript 动态加载内容并设有反爬虫措施,因此简单的 HTTP 请求未必能直接获得所需的数据[^1]。 #### 准备工作 安装必要的库: ```bash pip install requests beautifulsoup4 ``` #### 编写代码 下面是一个简单示例程序,展示如何使用 CSS 选择器豆瓣读书页面抓取书籍信息: ```python import requests from bs4 import BeautifulSoup url = 'https://book.douban.com/top250' headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" } response = requests.get(url, headers=headers) if response.status_code == 200: soup = BeautifulSoup(response.content.decode('utf-8'), 'html.parser') items = [] for item in soup.select('.item'): # 使用CSS选择器定位到每本书的信息块 title = item.select_one('.pl2 a')['title'] # 提取书名 rating_num = item.select_one('.rating_nums').text.strip() if item.select_one('.rating_nums') else '' book_info = {"Title": title, "Rating": rating_num} items.append(book_info) else: print(f"Failed to retrieve data with status code {response.status_code}") for i in items[:5]: print(i) ``` 这段代码首先发送了一个带有适当 User-Agent 头部的 GET 请求给指定 URL 来模拟浏览器行为;接着创建了 `BeautifulSoup` 对象用于解析 HTML 文档;最后运用 CSS 选择器选取特定元素完成数据抽取操作[^4]。 请注意,在实际应用中还需要考虑更多细节问题,比如异常处理、遵守robots协议以及应对更复杂的动态加载情况等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值