首页 > 编程语言 >爬虫小程序

爬虫小程序

时间:2023-02-05 13:11:15浏览次数:26  
标签:info name tags res 程序 爬虫 book print

豆瓣静态爬取

点击查看代码
# 导入 requests 库
import requests
# 从 bs4 库导入 BeautifulSoup
from bs4 import BeautifulSoup

# 定制消息头
headers = {
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
}
# 向 https://book.douban.com/top250/ 发送带消息头的请求
# 并将响应结果储存到 res 变量中
res = requests.get('https://book.douban.com/top250/', headers =headers)
#print(res)
# 将响应结果的文本内容解析为 BeautifulSoup 对象
# 并保存到变量 soup 中
#print(res.text)
soup = BeautifulSoup(res.text, 'html.parser')

# 所有书名所在元素
book_name_tags = soup.select('div.pl2 a')
#print(book_name_tags)
# 所有书籍信息所在元素
book_info_tags = soup.select('p.pl')
#print(book_info_tags)
# 遍历每本图书
for i in range(len(book_name_tags)):
  # 通过元素 title 属性提取书名
  name = book_name_tags[i]['title']
  # 获取书籍信息
  info = book_info_tags[i].text
  # 按“ / ”分割字符串
  info_list = info.split('/')
  # 结果列表中第一项为作者信息
  author = info_list[0]
  # 倒数第三项为出版社信息
  publisher = info_list[-3]
  # 打印书名、作者、出版社信息
  print(name, author, publisher)

标签:info,name,tags,res,程序,爬虫,book,print
From: https://www.cnblogs.com/v9193/p/17093227.html

相关文章