当前位置:   article > 正文

5分钟上手Python爬虫,轻松掌握爬虫技巧

5分钟上手Python爬虫,轻松掌握爬虫技巧

许多人对爬虫技术有所耳闻,我也不例外。之前看到过一些爬虫代码,虽然没有深入研究,但其强大功能给我留下了深刻印象。所以今天我决定从零开始,仅用5分钟入门爬虫技术,以后只需轻松一爬就能获取所有感兴趣的网站内容。广告?不存在的,因为爬虫只会获取我需要的信息,其他内容对我来说只是一堆代码。我们不关注网站的界面,只关注核心内容。

在这个过程中,技术本身并不复杂,更多的是一项需要耐心的工作。因此,许多人选择做爬虫兼职,因为尽管耗时较长,但技术门槛并不高。今天学完后,你就不会再觉得爬虫困难了。将来你可能需要考虑如何保持会话(session)或绕过验证等问题,因为有些网站并不希望被爬取,这部分内容最具挑战性,今后可以深入探讨。

今天我们以选择菜谱为例,解决生活中的“吃什么”难题。

爬虫解析

爬虫的原理类似于模拟用户浏览网站的操作:首先访问网站,检查是否有需要点击的链接,有则继续点击查看。当找到所需的图片或文字时,就可以下载或复制。这种爬虫的基本架构如图所示,希望这样的描述能帮助你更好地理解。

爬网页HTML

在爬虫工作中,第一步通常是发送一个HTTP请求以获取返回的数据。我们通常请求一个链接以获取JSON格式的信息以便处理。但对于爬虫来说,我们需要首先获取网页内容,这一步通常返回的是HTML页面。Python中有很多请求库,我这里举一个例子,你可以根据需求选择其他库,只要能完成任务即可。

在开始爬虫工作之前,需要安装所需的第三方库。这部分很简单,只需根据需要安装即可,没有复杂步骤。

让我们直接看代码示例:

  1. from urllib.request import urlopen, Request
  2. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'}
  3. req = Request("https://www.meishij.net/?from=space_block", headers=headers)
  4. html = urlopen(req)
  5. html_text = bytes.decode(html.read())
  6. print(html_text)

通常情况下,我们可以获取到这个菜谱网页的完整内容,就像在浏览器中按F12查看的网页源代码一样。

解析元素

最笨的方法是使用字符串解析,但Python有很多第三方库可以帮助我们,比如BeautifulSoup。其他解析方法不再赘述,需要什么就去搜索,记住常用的就好。

让我们解析热门搜索中的菜谱:

  1. from urllib.request import urlopen, Request
  2. from bs4 import BeautifulSoup as bf
  3. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'}
  4. req = Request("https://www.meishij.net/?from=space_block", headers=headers)
  5. html = urlopen(req)
  6. html_text = bytes.decode(html.read())
  7. obj = bf(html_text, 'html.parser')
  8. index_hotlist = obj.find_all('a', class_='sancan_item')
  9. for ul in index_hotlist:
  10. for li in ul.find_all('strong', class_='title'):
  11. print(li.get_text())

主要步骤是,先打印出HTML页面,通过观察确定所需内容位于哪个元素下,然后用BeautifulSoup定位并提取所需信息。这里我提取的是文字内容,成功提取了所有li列表元素。

随机干饭

选择吃什么是难题。我们可以将所有菜谱解析并存储在一个列表中,然后随机选择,这样就能轻松解决每顿饭吃什么的问题。

随机选取一道菜的代码示例:

  1. from urllib.request import urlopen, Request
  2. from bs4 import BeautifulSoup as bf
  3. for i in range(3):
  4. url = f"https://www.meishij.net/chufang/diy/jiangchangcaipu/?&page={i}"
  5. html = urlopen(url)
  6. html_text = bytes.decode(html.read())
  7. obj = bf(html_text, 'html.parser')
  8. index_hotlist = obj.find_all('img')
  9. for p in index_hotlist:
  10. if p.get('alt'):
  11. print(p.get('alt'))

这里我们在网站上找到了新的链接地址,获取了前三页的数据,并进行了随机选择,你也可以选择全部获取。

菜谱教程

上一步完成后,只需下单外卖了。但对于像我这样的顾家奶爸来说,外卖并不适合,所以必须自己做饭。这时候教程就显得尤为重要。

继续解析教程内容:

  1. from urllib.request import urlopen, Request
  2. import urllib, string
  3. from bs4 import BeautifulSoup as bf
  4. url = f"https://so.meishij.net/index.php?q=红烧排骨"
  5. url = urllib.parse.quote(url, safe=string.printable)
  6. html = urlopen(url)
  7. html_text = bytes.decode(html.read())
  8. obj = bf(html_text, 'html.parser')
  9. index_hotlist = obj.find_all('a', class_='img')
  10. url = index_hotlist[0].get('href')
  11. html = urlopen(url)
  12. html_text = bytes.decode(html.read())
  13. obj = bf(html_text, 'html.parser')
  14. index_hotlist = obj.find_all('div', class_='step_content')
  15. for div in index_hotlist:
  16. for p in div.find_all('p'):
  17. print(p.get_text())

包装一下

上述方法已经满足需求,但重复手动执行并不高效。所以,将这些步骤封装成一个简单的应用程序,这个应用程序使用控制台作为用户界面,不依赖任何第三方库。以下是应用程序代码:

  1. from urllib.request import urlopen, Request
  2. import urllib, string
  3. from bs4 import BeautifulSoup as bf
  4. from random import choice, sample
  5. from colorama import init
  6. from os import system
  7. from termcolor import colored
  8. from readchar import readkey
  9. FGS = ['green', 'yellow', 'blue', 'cyan', 'magenta', 'red']
  10. print(colored('搜索食谱中.....', choice(FGS)))
  11. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'}
  12. req = Request("https://www.meishij.net/?from=space_block", headers=headers)
  13. html = urlopen(req)
  14. html_text = bytes.decode(html.read())
  15. hot_list = []
  16. all_food = []
  17. food_page = 3
  18. def draw_menu(menu_list):
  19. clear()
  20. for idx, i in enumerate(menu_list):
  21. print(colored(f'{idx}:{i}', choice(FGS)))
  22. print(colored('8:随机选择', choice(FGS)))
  23. def draw_word(word_list):
  24. clear()
  25. for i in word_list:
  26. print(colored(i, choice(FGS)))
  27. def clear():
  28. system("CLS")
  29. def hot_list_func():
  30. global html_text
  31. obj = bf(html_text, 'html.parser')
  32. index_hotlist = obj.find_all('a', class_='sancan_item')
  33. for ul in index_hotlist:
  34. for li in ul.find_all('strong', class_='title'):
  35. hot_list.append(li.get_text())
  36. def search_food_detail(food):
  37. print('正在搜索详细教程,请稍等30秒左右!')
  38. url = f"https://so.meishij.net/index.php?q={food}"
  39. url = urllib.parse.quote(url, safe=string.printable)
  40. html = urlopen(url)
  41. html_text = bytes.decode(html.read())
  42. obj = bf(html_text, 'html.parser')
  43. index_hotlist = obj.find_all('a', class_='img')
  44. url = index_hotlist[0].get('href')
  45. html = urlopen(url)
  46. html_text = bytes.decode(html.read())
  47. obj = bf(html_text, 'html.parser')
  48. print(colored(f"{food}做法:", choice(FGS)))
  49. index_hotlist = obj.find_all('div', class_='step_content')
  50. for div in index_hotlist:
  51. for p in div.find_all('p'):
  52. print(colored(p.get_text(), choice(FGS)))
  53. def get_random_food():
  54. global food_page
  55. if not all_food:
  56. for i in range(food_page):
  57. url = f"https://www.meishij.net/chufang/diy/jiangchangcaipu/?&page={i}"
  58. html = urlopen(url)
  59. html_text = bytes.decode(html.read())
  60. obj = bf(html_text, 'html.parser')
  61. index_hotlist = obj.find_all('img')
  62. for p in index_hotlist:
  63. if p.get('alt'):
  64. all_food.append(p.get('alt'))
  65. my_food = choice(all_food)
  66. print(colored(f'随机选择,今天吃:{my_food}', choice(FGS)))
  67. return
  68. return my_food
  69. init() # 命令行输出彩色文字
  70. hot_list_func()
  71. print(colored('已搜索完毕!', choice(FGS)))
  72. my_array = list(range(0, 9))
  73. my_key = ['q', 'c', 'd', 'm']
  74. my_key.extend(my_array)
  75. print(colored('m:代表今日菜谱', choice(FGS)))
  76. print(colored('c:代表清空控制台', choice(FGS)))
  77. print(colored('d:代表菜谱教程', choice(FGS)))
  78. print(colored('q:退出菜谱', choice(FGS)))
  79. print(colored('0~8:选择菜谱中的菜', choice(FGS)))
  80. while True:
  81. while True:
  82. move = readkey()
  83. if move in my_key or (move.isdigit() and int(move) <= len(random_food)):
  84. break
  85. if move == 'q': # 键盘‘Q’是退出
  86. break
  87. if move == 'c': # 键盘‘C’是清空控制台
  88. clear()
  89. if move == 'm':
  90. random_food = sample(hot_list, 8)
  91. draw_menu(random_food)
  92. if move.isdigit() and int(move) <= len(random_food):
  93. if int(move) == 8:
  94. my_food = get_random_food()
  95. else:
  96. my_food = random_food[int(move)]
  97. print(my_food)
  98. if move == 'd' and my_food: # 键盘‘D’是查看教程
  99. search_food_detail(my_food)
  100. my_food = ''

完成一个简单的小爬虫并不复杂

只需要5分钟即可入门爬虫技术,开始爬取某个网站的数据实际上是一项细致的工作。只需在网上搜索相关技术信息,找到适合的方法即可,如果有效就继续使用,不行就试试其他方法。

总结

本文的重点在于引导读者初步掌握爬虫技术。入门并不难,但在实际操作中可能会遇到一些困难,比如有些网站不允许直接访问,需要登录或进行人机验证等。因此,建议先从爬取一些新闻资讯类的网站开始,因为这样相对容易。涉及用户支付等敏感信息的网站就不那么容易获取了。因此,在入门阶段,不要选择太复杂的网站,先尝试简单的爬取。一旦理解了基本原理,遇到问题时可以考虑添加组件或使用第三方库来解决。

最后一个综合示例

下面是一个完整的综合示例,封装了上述功能:

  1. from urllib.request import urlopen, Request
  2. import urllib, string
  3. from bs4 import BeautifulSoup as bf
  4. from random import choice, sample
  5. from colorama import init
  6. from os import system
  7. from termcolor import colored
  8. from readchar import readkey
  9. # 初始化彩色输出
  10. init()
  11. # 定义颜色
  12. FGS = ['green', 'yellow', 'blue', 'cyan', 'magenta', 'red']
  13. # 打印初始信息
  14. print(colored('搜索食谱中.....', choice(FGS)))
  15. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'}
  16. req = Request("https://www.meishij.net/?from=space_block", headers=headers)
  17. html = urlopen(req)
  18. html_text = bytes.decode(html.read())
  19. hot_list = []
  20. all_food = []
  21. food_page = 3
  22. def draw_menu(menu_list):
  23. clear()
  24. for idx, i in enumerate(menu_list):
  25. print(colored(f'{idx}:{i}', choice(FGS)))
  26. print(colored('8:随机选择', choice(FGS)))
  27. def draw_word(word_list):
  28. clear()
  29. for i in word_list:
  30. print(colored(i, choice(FGS)))
  31. def clear():
  32. system("CLS")
  33. def hot_list_func():
  34. global html_text
  35. obj = bf(html_text, 'html.parser')
  36. index_hotlist = obj.find_all('a', class_='sancan_item')
  37. for ul in index_hotlist:
  38. for li in ul.find_all('strong', class_='title'):
  39. hot_list.append(li.get_text())
  40. def search_food_detail(food):
  41. print('正在搜索详细教程,请稍等30秒左右!')
  42. url = f"https://so.meishij.net/index.php?q={food}"
  43. url = urllib.parse.quote(url, safe=string.printable)
  44. html = urlopen(url)
  45. html_text = bytes.decode(html.read())
  46. obj = bf(html_text, 'html.parser')
  47. index_hotlist = obj.find_all('a', class_='img')
  48. url = index_hotlist[0].get('href')
  49. html = urlopen(url)
  50. html_text = bytes.decode(html.read())
  51. obj = bf(html_text, 'html.parser')
  52. print(colored(f"{food}做法:", choice(FGS)))
  53. index_hotlist = obj.find_all('div', class_='step_content')
  54. for div in index_hotlist:
  55. for p in div.find_all('p'):
  56. print(colored(p.get_text(), choice(FGS)))
  57. def get_random_food():
  58. global food_page
  59. if not all_food:
  60. for i in range(food_page):
  61. url = f"https://www.meishij.net/chufang/diy/jiangchangcaipu/?&page={i}"
  62. html = urlopen(url)
  63. html_text = bytes.decode(html.read())
  64. obj = bf(html_text, 'html.parser')
  65. index_hotlist = obj.find_all('img')
  66. for p in index_hotlist:
  67. if p.get('alt'):
  68. all_food.append(p.get('alt'))
  69. my_food = choice(all_food)
  70. print(colored(f'随机选择,今天吃:{my_food}', choice(FGS)))
  71. return my_food
  72. # 初始化并获取热门菜谱
  73. hot_list_func()
  74. print(colored('已搜索完毕!', choice(FGS)))
  75. # 定义按键操作
  76. my_array = list(range(0, 9))
  77. my_key = ['q', 'c', 'd', 'm']
  78. my_key.extend(my_array)
  79. print(colored('m:代表今日菜谱', choice(FGS)))
  80. print(colored('c:代表清空控制台', choice(FGS)))
  81. print(colored('d:代表菜谱教程', choice(FGS)))
  82. print(colored('q:退出菜谱', choice(FGS)))
  83. print(colored('0~8:选择菜谱中的菜', choice(FGS)))
  84. while True:
  85. while True:
  86. move = readkey()
  87. if move in my_key or (move.isdigit() and int(move) <= len(random_food)):
  88. break
  89. if move == 'q':
  90. break
  91. if move == 'c':
  92. clear()
  93. if move == 'm':
  94. random_food = sample(hot_list, 8)
  95. draw_menu(random_food)
  96. if move.isdigit() and int(move) <= len(random_food):
  97. if int(move) == 8:
  98. my_food = get_random_food()
  99. else:
  100. my_food = random_food[int(move)]
  101. print(my_food)
  102. if move == 'd' and my_food:
  103. search_food_detail(my_food)
  104. my_food = ''

以上代码完整展示了如何从选择菜谱、随机挑选菜谱到获取详细做法教程,并将这些功能封装到一个简易的控制台应用程序中。通过这个项目,你应该对爬虫技术有了初步的认识和实际操作经验。今后,可以根据需要逐步深入学习爬虫技术的高级内容,如保持会话、绕过验证等。

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

闽ICP备14008679号