赞
踩
许多人对爬虫技术有所耳闻,我也不例外。之前看到过一些爬虫代码,虽然没有深入研究,但其强大功能给我留下了深刻印象。所以今天我决定从零开始,仅用5分钟入门爬虫技术,以后只需轻松一爬就能获取所有感兴趣的网站内容。广告?不存在的,因为爬虫只会获取我需要的信息,其他内容对我来说只是一堆代码。我们不关注网站的界面,只关注核心内容。
在这个过程中,技术本身并不复杂,更多的是一项需要耐心的工作。因此,许多人选择做爬虫兼职,因为尽管耗时较长,但技术门槛并不高。今天学完后,你就不会再觉得爬虫困难了。将来你可能需要考虑如何保持会话(session)或绕过验证等问题,因为有些网站并不希望被爬取,这部分内容最具挑战性,今后可以深入探讨。
今天我们以选择菜谱为例,解决生活中的“吃什么”难题。
爬虫的原理类似于模拟用户浏览网站的操作:首先访问网站,检查是否有需要点击的链接,有则继续点击查看。当找到所需的图片或文字时,就可以下载或复制。这种爬虫的基本架构如图所示,希望这样的描述能帮助你更好地理解。
在爬虫工作中,第一步通常是发送一个HTTP请求以获取返回的数据。我们通常请求一个链接以获取JSON格式的信息以便处理。但对于爬虫来说,我们需要首先获取网页内容,这一步通常返回的是HTML页面。Python中有很多请求库,我这里举一个例子,你可以根据需求选择其他库,只要能完成任务即可。
在开始爬虫工作之前,需要安装所需的第三方库。这部分很简单,只需根据需要安装即可,没有复杂步骤。
让我们直接看代码示例:
- from urllib.request import urlopen, Request
-
- 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'}
- req = Request("https://www.meishij.net/?from=space_block", headers=headers)
- html = urlopen(req)
- html_text = bytes.decode(html.read())
- print(html_text)
通常情况下,我们可以获取到这个菜谱网页的完整内容,就像在浏览器中按F12查看的网页源代码一样。
最笨的方法是使用字符串解析,但Python有很多第三方库可以帮助我们,比如BeautifulSoup。其他解析方法不再赘述,需要什么就去搜索,记住常用的就好。
让我们解析热门搜索中的菜谱:
- from urllib.request import urlopen, Request
- from bs4 import BeautifulSoup as bf
-
- 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'}
- req = Request("https://www.meishij.net/?from=space_block", headers=headers)
- html = urlopen(req)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('a', class_='sancan_item')
-
- for ul in index_hotlist:
- for li in ul.find_all('strong', class_='title'):
- print(li.get_text())
主要步骤是,先打印出HTML页面,通过观察确定所需内容位于哪个元素下,然后用BeautifulSoup定位并提取所需信息。这里我提取的是文字内容,成功提取了所有li列表元素。
选择吃什么是难题。我们可以将所有菜谱解析并存储在一个列表中,然后随机选择,这样就能轻松解决每顿饭吃什么的问题。
随机选取一道菜的代码示例:
- from urllib.request import urlopen, Request
- from bs4 import BeautifulSoup as bf
-
- for i in range(3):
- url = f"https://www.meishij.net/chufang/diy/jiangchangcaipu/?&page={i}"
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('img')
- for p in index_hotlist:
- if p.get('alt'):
- print(p.get('alt'))
这里我们在网站上找到了新的链接地址,获取了前三页的数据,并进行了随机选择,你也可以选择全部获取。
上一步完成后,只需下单外卖了。但对于像我这样的顾家奶爸来说,外卖并不适合,所以必须自己做饭。这时候教程就显得尤为重要。
继续解析教程内容:
- from urllib.request import urlopen, Request
- import urllib, string
- from bs4 import BeautifulSoup as bf
-
- url = f"https://so.meishij.net/index.php?q=红烧排骨"
- url = urllib.parse.quote(url, safe=string.printable)
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('a', class_='img')
- url = index_hotlist[0].get('href')
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('div', class_='step_content')
-
- for div in index_hotlist:
- for p in div.find_all('p'):
- print(p.get_text())
上述方法已经满足需求,但重复手动执行并不高效。所以,将这些步骤封装成一个简单的应用程序,这个应用程序使用控制台作为用户界面,不依赖任何第三方库。以下是应用程序代码:
- from urllib.request import urlopen, Request
- import urllib, string
- from bs4 import BeautifulSoup as bf
- from random import choice, sample
- from colorama import init
- from os import system
- from termcolor import colored
- from readchar import readkey
-
- FGS = ['green', 'yellow', 'blue', 'cyan', 'magenta', 'red']
- print(colored('搜索食谱中.....', choice(FGS)))
- 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'}
- req = Request("https://www.meishij.net/?from=space_block", headers=headers)
- html = urlopen(req)
- html_text = bytes.decode(html.read())
- hot_list = []
- all_food = []
- food_page = 3
-
- def draw_menu(menu_list):
- clear()
- for idx, i in enumerate(menu_list):
- print(colored(f'{idx}:{i}', choice(FGS)))
- print(colored('8:随机选择', choice(FGS)))
-
- def draw_word(word_list):
- clear()
- for i in word_list:
- print(colored(i, choice(FGS)))
-
- def clear():
- system("CLS")
-
- def hot_list_func():
- global html_text
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('a', class_='sancan_item')
- for ul in index_hotlist:
- for li in ul.find_all('strong', class_='title'):
- hot_list.append(li.get_text())
-
- def search_food_detail(food):
- print('正在搜索详细教程,请稍等30秒左右!')
- url = f"https://so.meishij.net/index.php?q={food}"
- url = urllib.parse.quote(url, safe=string.printable)
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('a', class_='img')
- url = index_hotlist[0].get('href')
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- print(colored(f"{food}做法:", choice(FGS)))
- index_hotlist = obj.find_all('div', class_='step_content')
- for div in index_hotlist:
- for p in div.find_all('p'):
- print(colored(p.get_text(), choice(FGS)))
-
- def get_random_food():
- global food_page
- if not all_food:
- for i in range(food_page):
- url = f"https://www.meishij.net/chufang/diy/jiangchangcaipu/?&page={i}"
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('img')
- for p in index_hotlist:
- if p.get('alt'):
- all_food.append(p.get('alt'))
- my_food = choice(all_food)
- print(colored(f'随机选择,今天吃:{my_food}', choice(FGS)))
- return
- return my_food
-
- init() # 命令行输出彩色文字
- hot_list_func()
- print(colored('已搜索完毕!', choice(FGS)))
- my_array = list(range(0, 9))
- my_key = ['q', 'c', 'd', 'm']
- my_key.extend(my_array)
- print(colored('m:代表今日菜谱', choice(FGS)))
- print(colored('c:代表清空控制台', choice(FGS)))
- print(colored('d:代表菜谱教程', choice(FGS)))
- print(colored('q:退出菜谱', choice(FGS)))
- print(colored('0~8:选择菜谱中的菜', choice(FGS)))
-
- while True:
- while True:
- move = readkey()
- if move in my_key or (move.isdigit() and int(move) <= len(random_food)):
- break
- if move == 'q': # 键盘‘Q’是退出
- break
- if move == 'c': # 键盘‘C’是清空控制台
- clear()
- if move == 'm':
- random_food = sample(hot_list, 8)
- draw_menu(random_food)
- if move.isdigit() and int(move) <= len(random_food):
- if int(move) == 8:
- my_food = get_random_food()
- else:
- my_food = random_food[int(move)]
- print(my_food)
- if move == 'd' and my_food: # 键盘‘D’是查看教程
- search_food_detail(my_food)
- my_food = ''
只需要5分钟即可入门爬虫技术,开始爬取某个网站的数据实际上是一项细致的工作。只需在网上搜索相关技术信息,找到适合的方法即可,如果有效就继续使用,不行就试试其他方法。
本文的重点在于引导读者初步掌握爬虫技术。入门并不难,但在实际操作中可能会遇到一些困难,比如有些网站不允许直接访问,需要登录或进行人机验证等。因此,建议先从爬取一些新闻资讯类的网站开始,因为这样相对容易。涉及用户支付等敏感信息的网站就不那么容易获取了。因此,在入门阶段,不要选择太复杂的网站,先尝试简单的爬取。一旦理解了基本原理,遇到问题时可以考虑添加组件或使用第三方库来解决。
下面是一个完整的综合示例,封装了上述功能:
- from urllib.request import urlopen, Request
- import urllib, string
- from bs4 import BeautifulSoup as bf
- from random import choice, sample
- from colorama import init
- from os import system
- from termcolor import colored
- from readchar import readkey
-
- # 初始化彩色输出
- init()
-
- # 定义颜色
- FGS = ['green', 'yellow', 'blue', 'cyan', 'magenta', 'red']
-
- # 打印初始信息
- print(colored('搜索食谱中.....', choice(FGS)))
- 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'}
- req = Request("https://www.meishij.net/?from=space_block", headers=headers)
- html = urlopen(req)
- html_text = bytes.decode(html.read())
- hot_list = []
- all_food = []
- food_page = 3
-
- def draw_menu(menu_list):
- clear()
- for idx, i in enumerate(menu_list):
- print(colored(f'{idx}:{i}', choice(FGS)))
- print(colored('8:随机选择', choice(FGS)))
-
- def draw_word(word_list):
- clear()
- for i in word_list:
- print(colored(i, choice(FGS)))
-
- def clear():
- system("CLS")
-
- def hot_list_func():
- global html_text
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('a', class_='sancan_item')
- for ul in index_hotlist:
- for li in ul.find_all('strong', class_='title'):
- hot_list.append(li.get_text())
-
- def search_food_detail(food):
- print('正在搜索详细教程,请稍等30秒左右!')
- url = f"https://so.meishij.net/index.php?q={food}"
- url = urllib.parse.quote(url, safe=string.printable)
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('a', class_='img')
- url = index_hotlist[0].get('href')
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- print(colored(f"{food}做法:", choice(FGS)))
- index_hotlist = obj.find_all('div', class_='step_content')
- for div in index_hotlist:
- for p in div.find_all('p'):
- print(colored(p.get_text(), choice(FGS)))
-
- def get_random_food():
- global food_page
- if not all_food:
- for i in range(food_page):
- url = f"https://www.meishij.net/chufang/diy/jiangchangcaipu/?&page={i}"
- html = urlopen(url)
- html_text = bytes.decode(html.read())
- obj = bf(html_text, 'html.parser')
- index_hotlist = obj.find_all('img')
- for p in index_hotlist:
- if p.get('alt'):
- all_food.append(p.get('alt'))
- my_food = choice(all_food)
- print(colored(f'随机选择,今天吃:{my_food}', choice(FGS)))
- return my_food
-
- # 初始化并获取热门菜谱
- hot_list_func()
- print(colored('已搜索完毕!', choice(FGS)))
-
- # 定义按键操作
- my_array = list(range(0, 9))
- my_key = ['q', 'c', 'd', 'm']
- my_key.extend(my_array)
- print(colored('m:代表今日菜谱', choice(FGS)))
- print(colored('c:代表清空控制台', choice(FGS)))
- print(colored('d:代表菜谱教程', choice(FGS)))
- print(colored('q:退出菜谱', choice(FGS)))
- print(colored('0~8:选择菜谱中的菜', choice(FGS)))
-
- while True:
- while True:
- move = readkey()
- if move in my_key or (move.isdigit() and int(move) <= len(random_food)):
- break
- if move == 'q':
- break
- if move == 'c':
- clear()
- if move == 'm':
- random_food = sample(hot_list, 8)
- draw_menu(random_food)
- if move.isdigit() and int(move) <= len(random_food):
- if int(move) == 8:
- my_food = get_random_food()
- else:
- my_food = random_food[int(move)]
- print(my_food)
- if move == 'd' and my_food:
- search_food_detail(my_food)
- my_food = ''
以上代码完整展示了如何从选择菜谱、随机挑选菜谱到获取详细做法教程,并将这些功能封装到一个简易的控制台应用程序中。通过这个项目,你应该对爬虫技术有了初步的认识和实际操作经验。今后,可以根据需要逐步深入学习爬虫技术的高级内容,如保持会话、绕过验证等。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。