- 欢迎来到“Python 爬虫入门”系列的第一篇文章。你有没有想过,怎么能从网页上自动抓取你需要的数据?比如,一次性下载所有喜欢的图片,或者获取最新的新闻资讯。其实,这就是网络爬虫能做的事情。
- Python 是一门非常受欢迎的编程语言,简单易学,而且有很多强大的库可以用来编写网络爬虫。即使你是编程新手,也不用担心,这个系列会从最基础的知识讲起,带你一步步掌握写爬虫的技能。
- 在这篇文章里,我们会先聊聊什么是网络爬虫,它是怎么工作的,然后教你如何安装和配置开发环境、如何使用 Python 编写爬虫脚本。
网络爬虫,也称为网络蜘蛛、网络机器人,是一种自动化脚本或程序,用于自动浏览互联网并收集数据。
爬虫可以帮助我们从网页中提取信息,从而实现数据采集、信息检索、网站分析等功能。
HTTP(HyperText Transfer Protocol)是用于在 Web 浏览器和 Web服务器之间传递信息的协议。它是一种基于请求 - 响应模式的协议,客户端发送请求,服务器返回响应。
HTTP 请求由以下几个部分组成:
HTTP 响应由以下几个部分组成:
一个典型的网页由以下几个部分组成:
HTML(HyperText Markup Language)是用于创建和结构化网页内容的标准标记语言。HTML 使用标签来标记不同类型的内容,如文本、图像、链接等。
HTML 基础结构示例如下:
Document Hello, World!
Welcome to my website.
CSS(Cascading Style Sheets)是一种样式表语言,用于描述 HTML 文档的外观和格式。CSS 可以控制网页的布局、颜色、字体等。
CSS 示例如下:
body { font-family: Arial, sans-serif; } h1 { color: blue; } p { font-size: 16px; }
JavaScript 是一种高效的编程语言,通常用于网页开发,可以使网页具有动态交互功能。JavaScript 可以操作 HTML 和 CSS,响应用户事件,创建动态效果等。
JavaScript 示例如下:
document.addEventListener('DOMContentLoaded', function() { const button = document.getElementById('myButton'); button.addEventListener('click', function() { alert('Button clicked!'); }); });
使用 pip 安装下列库:
pip install requests pip install beautifulsoup4 pip install scrapy pip install openpyxl pip install playwright python -m playwright install
下面是一个使用 requests 编写的简单爬虫示例。
import requests # 发送请求 url = 'https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total' response = requests.get(url) # 解析JSON数据 data = response.json() if 'data' in data: # 遍历数据 for item in data['data']: if 'target' in item and 'title' in item['target']: print(item['target']['title']) else: print("没有获取到数据")
执行结果如下:
对于一些动态加载内容的网页,仅靠 requests 和 BeautifulSoup 可能无法获取所有数据。这时可以使用 Playwright 模拟浏览器操作。
import asyncio from bs4 import BeautifulSoup from playwright.async_api import async_playwright async def run(playwright: async_playwright) -> None: browser = await playwright.chromium.launch(headless=False) context = await browser.new_context() page = await context.new_page() # 访问网页 await page.goto('https://nba.hupu.com/') # 获取页面内容 content = await page.content() # 解析 HTML(同样使用 BeautifulSoup) soup = BeautifulSoup(content, 'html.parser') # 提取页面标题 title = soup.title.string print('Title:', title) # 提取推荐文章的标题及链接 links = await page.locator('.list-recommend a, .list-container a').all() for link in links: title = await link.inner_text() href = await link.get_attribute('href') print(title, href) # 关闭浏览器和上下文 await context.close() await browser.close() # 异步运行函数 async def main(): async with async_playwright() as playwright: await run(playwright) # 运行主函数 asyncio.run(main())
下面,我们将编写一个完整的爬虫项目,从一个网站中提取数据并保存到本地文件。
下面是一个使用 requests 和 BeautifulSoup 编写的爬虫示例。
import requests from bs4 import BeautifulSoup from openpyxl import Workbook from pathlib import Path def showStart(city_code): # 发送请求获取网页内容 url = f'https://www.showstart.com/event/list?pageNo=1&pageSize=99999&cityCode={city_code}' response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') items = soup.find_all('a', class_='show-item item') # 创建Excel工作簿 wb = Workbook() sheet = wb.active # 添加标题行 sheet.append(['标题', '艺人', '价格', '时间', '地址', '链接']) for item in items: title = item.find('div', class_='title').text.strip() artist = item.find('div', class_='artist').text.strip() price = item.find('div', class_='price').text.strip() time = item.find('div', class_='time').text.strip() addr = item.find('div', class_='addr').text.strip() href = 'https://www.showstart.com' + item['href'] # 将数据写入Excel sheet.append([title, artist, price, time, addr, href]) # 保存Excel文件 root_dir = Path(__file__).resolve().parent file_path = root_dir / f'showstart_{city_code}.xlsx' wb.save(file_path) print(f'数据已保存到 {file_path}') else: print(f'请求失败,状态码:{response.status_code}') if __name__ == "__main__": city_code = input("请输入城市编码:") showStart(city_code)
打开Excel 文件,内容如下:
robots.txt 文件是一个文本文件,通常放置在网站的根目录下。
它用来告诉搜索引擎的爬虫(spider)哪些页面可以抓取,哪些页面不可以抓取。
要找到网站的 robots.txt 文件,在浏览器的地址栏输入以下格式的URL:
http://www.xxx.com/robots.txt
如果访问的是不带www的域名:
http://xxx.com/robots.txt
希望你通过本文,对 Python 爬虫有了一个全面的了解。我们从 Python 爬虫的基本概念、HTTP 基础知识以及网页的基本组成部分讲起,逐步学习了如何使用 Python 编写简单的爬虫,以及如何处理动态加载内容的网页。最后,我们用一个完整的爬虫项目,把学到的知识都串联起来,实战演练了一遍。相信通过这次学习,你对爬虫的工作流程和技术细节都有了更深入的理解。
如果你有任何问题或者好的想法,欢迎随时和我交流。
上一篇:公有云计算_计算