用python爬取蔚蓝书店https://www.welan.com/上的数据 ,采集的内容有图书封面、书名、ISBN、作者、价格、出版日期、出版社等。将爬取到的数据存储在MongoDB中
时间: 2024-06-08 12:12:26 浏览: 11
好的,你需要安装pymongo和beautifulsoup4这两个库来完成任务。可以使用以下命令进行安装:
```
pip install pymongo
pip install beautifulsoup4
```
然后就可以开始编写爬虫程序了。
```python
import requests
from bs4 import BeautifulSoup
import pymongo
# 连接MongoDB数据库
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["bookstore"]
collection = db["books"]
# 爬取页面的URL
url = "https://www.welan.com/"
# 发送请求获取页面内容
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(html, "html.parser")
# 获取图书列表
book_list = soup.find_all("div", class_="book-item")
# 遍历图书列表,提取信息并存储到MongoDB中
for book in book_list:
# 获取图书封面URL
cover_url = book.find("img")["src"]
# 获取图书信息
title = book.find("div", class_="title").text.strip()
isbn = book.find("div", class_="isbn").text.strip()
author = book.find("div", class_="author").text.strip()
price = book.find("div", class_="price").text.strip()
pub_date = book.find("div", class_="pub-date").text.strip()
publisher = book.find("div", class_="publisher").text.strip()
# 存储到MongoDB中
book_data = {
"cover_url": cover_url,
"title": title,
"isbn": isbn,
"author": author,
"price": price,
"pub_date": pub_date,
"publisher": publisher
}
collection.insert_one(book_data)
```
这段代码首先连接到本地的MongoDB数据库,然后发送请求获取页面内容,并使用BeautifulSoup解析页面。接着遍历图书列表,提取信息,并将其存储到MongoDB中。最后,你就可以在MongoDB中查看采集到的数据了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)