当前位置:   article > 正文

python爬虫:爬取网站所有页面上某些内容_python 获取页元素中的内容

python 获取页元素中的内容

举例场景:爬取腾讯课堂中,查询python的所有课程的封面图、课程标题、课程数量、课程价格,这4个部分的内容。

代码如下:

  1. import requests
  2. # import lxml # 导入用于请求的包lxml
  3. from bs4 import BeautifulSoup # 导入用于请求的包bs4
  4. from math import ceil # 向上取整
  5. from pprint import pprint
  6. BASE_URL = "https://ke.qq.com/course/list/python" # 腾讯课堂的网站,搜索python的第一个页面
  7. def get_content(url:str):
  8. """对某一个url进行http请求,获取返回的文本"""
  9. header = {'user-agent':"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"}
  10. response = requests.get(url, headers=header)
  11. response_text = response.content.decode("utf-8")
  12. return response_text
  13. def get_pages(one_page_num:int):
  14. """计算网页的总页数"""
  15. content = get_content(BASE_URL)
  16. # 实例化bs4对象
  17. soup = BeautifulSoup(content, 'lxml')
  18. # 找到页面上显示的总结果数
  19. total_courses = int(soup.find('em', class_="result__count").text.replace("+", "")) # 去掉数字后面的+,例如,200+
  20. # 计算中页数,向上取整
  21. return ceil(total_courses/one_page_num)
  22. def get_pages_url(pages:int):
  23. """拼接每一页的url"""
  24. # 定义一个页面url存放的list
  25. url_list = []
  26. for page in range(1, pages+1):
  27. url_list.append(BASE_URL + '?page=' + str(page))
  28. return url_list
  29. def get_info(url:str):
  30. """抓取某个页面的内容:封面图、课程标题、课程数量、课程价格"""
  31. content = get_content(url) # 腾讯课堂的网站,搜索python,一页上抓取某些内容
  32. # 实例化bs4对象
  33. soup = BeautifulSoup(content, 'lxml')
  34. # 第一次筛选
  35. first_filter = soup.find_all('div', class_='course-list')[0] # 仅又一个值,注意class后面带有下划线_
  36. # 第二次筛选
  37. second_filter = first_filter.find_all('section', class_="course-card-expo-wrapper") # 一页中共有24个值
  38. # print(len(second_filter))
  39. # print(second_filter)
  40. # 定一个集合,使用循环来遍历第二次抓取出的内容
  41. page_info = []
  42. for one in second_filter:
  43. temp_dict = {}
  44. # 抓取封面图片地址
  45. img = one.find('div', class_="kc-course-card-cover").img.attrs['src']
  46. # img = one.find('div', class_="kc-course-card-cover").find('img').attrs['src']
  47. temp_dict["img"] = img
  48. # 抓取课程title
  49. title = one.find('div', class_="kc-course-card-content").h3.attrs['title']
  50. temp_dict['title'] = title
  51. # 抓取课程数量
  52. try: # 有的课程没有展示课程数量,找不到对应的字段信息,因此添加一个异常捕获
  53. course_num = one.find('div', class_="kc-course-card-cover-course-num---tapHtg").text
  54. except AttributeError as e:
  55. pprint(e)
  56. temp_dict['course_num'] = "没有在展示出课程数量"
  57. else:
  58. temp_dict['course_num'] = course_num
  59. # 抓取课程价格
  60. price = one.find('span', class_="kc-course-card-price").text
  61. temp_dict['price'] = price
  62. # 添加到集合中
  63. page_info.append(temp_dict)
  64. return page_info
  65. def get_all_info(urls:list):
  66. """抓取所有页面的内容"""
  67. # 定义一个list存放所有页面上抓取到的内容
  68. all_info = []
  69. for url in urls:
  70. # 抓取某一页的内容,extend在列表末尾扩展序列元素
  71. all_info.extend(get_info(url))
  72. return all_info
  73. if __name__ == '__main__':
  74. # 一页展示的数量
  75. one_page_num = 24
  76. # 计算总页数
  77. pages = get_pages(one_page_num)
  78. # 获取所有页的url
  79. urls = get_pages_url(pages)
  80. # 抓取所有页面的内容
  81. results = get_all_info(urls)
  82. # 打印抓取总课程数量
  83. pprint(len(results))
  84. # 循环打印出抓取的每门课程的课程数量
  85. for one in results:
  86. pprint(one['course_num'])

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/960498
推荐阅读
相关标签
  

闽ICP备14008679号