爬取豆瓣图书top250
时间: 2023-10-23 16:15:10 浏览: 34
好的,你可以使用 Python 的 requests 和 BeautifulSoup 库来爬取豆瓣图书 top250 的信息。
首先,你需要用 requests 库向豆瓣图书 top250 的网页发送请求,并将返回的 HTML 代码保存到一个变量中。代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://book.douban.com/top250'
response = requests.get(url)
html = response.text
```
接着,你需要使用 BeautifulSoup 库来解析 HTML 代码,并提取出书籍的信息。代码如下:
```python
soup = BeautifulSoup(html, 'html.parser')
book_list = soup.find('div', {'class': 'article'}).find('div', {'class': 'indent'}).find('table')
for book in book_list.find_all('tr'):
book_info = book.find('td', {'valign': 'top'})
book_name = book_info.find('div', {'class': 'pl2'}).find('a').text.strip()
book_author = book_info.find('p', {'class': 'pl'}).text.strip()
book_rating = book_info.find('div', {'class': 'star clearfix'}).find('span', {'class': 'rating_nums'}).text.strip()
book_intro = book_info.find('span', {'class': 'inq'}).text.strip()
print('书名:', book_name)
print('作者:', book_author)
print('评分:', book_rating)
print('简介:', book_intro)
```
上面的代码将会输出豆瓣图书 top250 中每本书的书名、作者、评分和简介。你可以根据需要对代码进行修改,以适应你的爬取需求。