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

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

利用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 so
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一份简单的Python代码,用于爬取豆瓣图书信息: ```python import requests from bs4 import BeautifulSoup def get_book_info(url): # 发送请求并解析页面 res = requests.get(url) soup = BeautifulSoup(res.text, 'html.parser') # 获取书名、作者、出版社、出版日期、价格、评分和评论数 book_name = soup.select_one('h1 > span').text author = soup.select_one('.info > span:nth-child(1) > a').text publisher = soup.select_one('.info > span:nth-child(2)').text.strip() pub_date = soup.select_one('.info > span:nth-child(3)').text.strip() price = soup.select_one('.info > span:nth-child(4)').text.strip() rating = soup.select_one('.rating_num').text.strip() comments = soup.select_one('.rating_sum > a').text.strip() # 打印结果 print('书名:', book_name) print('作者:', author) print('出版社:', publisher) print('出版日期:', pub_date) print('价格:', price) print('评分:', rating) print('评论数:', comments) if __name__ == '__main__': url = 'https://book.douban.com/subject/1084336/' get_book_info(url) ``` 在上面的代码中,我们使用了Python中的requests库和BeautifulSoup库。requests库用于发送HTTP请求,获取网页内容,而BeautifulSoup库则用于解析HTML页面,提取我们需要的信息。 在get_book_info函数中,我们首先发送了一个HTTP GET请求,获取了豆瓣图书的页面内容。然后,我们使用BeautifulSoup库解析页面,通过CSS选择器选择需要的元素,并使用.text属性获取文本内容。 最后,我们打印了获取到的图书信息。您可以将上面的代码复制到您的Python环境中并运行,以查看结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值