帮我写一个Python爬虫爬取豆瓣小说数据
请注意,豆瓣网站有反爬虫机制,所以在编写爬虫时必须遵守网站的规定,并采取一些策略来避免被检测出来。
以下是一个简单的Python爬虫示例,可以爬取豆瓣小说的基本信息(书名、作者、评分、评论数等):
import requests
from bs4 import BeautifulSoup
url = 'https://book.douban.com/tag/%E5%B0%8F%E8%AF%B4'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
books = soup.select('.subject-item')
for book in books:
title = book.select('h2 > a')[0].text.strip()
author = book.select('.pub')[0].text.strip().split('/')[0]
rating = book.select('.rating_nums')[0].text.strip()
comments = book.select('.pl')[0].text.strip()
print(title, author, rating, comments)
这个示例使用requests库来获取网页内容,使用BeautifulSoup库来解析HTML代码。
我们在headers中设置了User-Agent,这是一个伪装成浏览器的技巧,可以避免被网站检测到我们是一个爬虫。
在解析HTML代码后,我们使用CSS选择器来提取所需信息。在这个示例中,我们使用了.select()方法来选择需要的元素。
最后,我们打印出了每本书的信息。你可以根据自己的需求修改这个程序,例如加入翻页功能、保存数据到文件等等
原文地址: https://www.cveoy.top/t/topic/dVun 著作权归作者所有。请勿转载和采集!