要在Jupyter中提取网页内容,我们可以使用Python的requests和BeautifulSoup库。首先,我们需要安装这两个库。可以在Jupyter中使用以下命令进行安装:

!pip install requests
!pip install beautifulsoup4

安装完成后,我们可以开始编写代码。

首先,导入所需的库和模块:

import requests
from bs4 import BeautifulSoup

然后,使用requests库发送GET请求来获取网页内容:

url = 'https://book.douban.com/chart?subcat=art&icn=index-topchart-popular'
response = requests.get(url)

接下来,使用BeautifulSoup库解析网页内容:

soup = BeautifulSoup(response.text, 'html.parser')

我们可以使用开发者工具(Inspect)来查找书名和评分所在的HTML元素。例如,书名在<div class="pl2">标签下的<a>标签内,评分在<span class="rating_nums">标签内。

使用BeautifulSoup库提取书名和评分:

books = soup.find_all('div', class_='pl2')
for book in books:
    title = book.a.text.strip()
    rating = book.find('span', class_='rating_nums').text.strip()
    print('书名:', title)
    print('评分:', rating)
    print('---')

最后,运行代码即可获得提取的书名和评分。

完整的代码如下:

import requests
from bs4 import BeautifulSoup

url = 'https://book.douban.com/chart?subcat=art&icn=index-topchart-popular'
response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

books = soup.find_all('div', class_='pl2')
for book in books:
    title = book.a.text.strip()
    rating = book.find('span', class_='rating_nums').text.strip()
    print('书名:', title)
    print('评分:', rating)
    print('---')

希望能对你有所帮助

使用jupyter对以下网址httpsbookdoubancomchartsubcat=art&icn=index-topchart-popular进行书名评分提取

原文地址: https://www.cveoy.top/t/topic/hzgg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录