Python爬虫在数据获取和自动化任务中扮演着重要角色。本文简单介绍几种常见的基础Python爬虫方法,包括Urllib方法、requests方法、BS4- BeautifulSoup4或lxml解析网页、XPath语法、使用正则表达式进行信息提取和使用Selenium或Pyppeteer处理动态网页。 ### 几种常见Python基础爬虫方法介绍 #### 一、使用 Urllib 方法 Python 的 `urllib` 库是一个内置的 HTTP 请求库,用于处理 URL 和进行网络请求。尽管 `requests` 库因其简洁易用而受到广泛欢迎,但 `urllib` 也提供了必要的功能来满足基本的网络爬虫需求。 **1. 发送 GET 请求** ```python import urllib.request # 定位抓取的 URL url = 'http://www.baidu.com/' # 向目标 URL 发送请求 response = urllib.request.urlopen(url) # 读取数据 data = response.read() # 打印数据 print(data.decode('utf-8')) ``` **2. 发送 POST 请求** ```python import urllib.parse url = 'http://www.iqianyue.com/mypost/' # 构建上传的数据 postdata = urllib.parse.urlencode({'name': 'Jack', 'pass': '123456'}).encode('utf-8') html = urllib.request.urlopen(url, data=postdata).read() print(html) ``` **3. 设置请求头** 针对某些网站可能会检查请求头信息以防止爬虫的情况,可以通过以下方式设置自定义的 User-Agent: ```python import urllib.request headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } request = urllib.request.Request('https://www.dianping.com/', headers=headers) response = urllib.request.urlopen(request) print(response.read().decode('utf-8')) ``` **4. 超时设置与异常处理** 当访问网站速度较慢或服务器无响应时,可以设置超时时间,并进行异常处理: ```python import urllib.request import urllib.error for i in range(20): try: response = urllib.request.urlopen('http://www.ibeifeng.com/', timeout=0.01) print('成功') except urllib.error.URLError as e: print('URLError:', e) except Exception as a: print('其他异常:', a) ``` #### 二、使用 Requests 方法 `requests` 是一个非常流行的 Python HTTP 客户端库,它简化了 HTTP 请求的操作过程,使开发者能够更轻松地发送请求和获取网页内容。 **1. 发送 GET 请求** ```python import requests r = requests.get('https://www.taobao.com/') # 打印文本数据 print(r.text) # 获取网页编码 import chardet print(chardet.detect(r.content)) ``` **2. 发送 POST 请求** 模拟表单登录通常需要发送 POST 请求,这里展示如何使用 `requests` 来实现: ```python import requests # 构建上传到网页的数据 data = {'username': 'example_user', 'password': 'example_password'} r = requests.post('https://www.example.com/login', data=data) print(r.text) ``` **总结** 通过以上示例可以看出,无论是使用 `urllib` 还是 `requests`,都可以有效地完成网络请求的基本操作。其中,`requests` 提供了更加简洁和用户友好的 API,因此对于大多数应用场景来说,`requests` 更为推荐。 接下来,我们将继续介绍其他几种常见的基础 Python 爬虫方法,包括使用 `BeautifulSoup4` 或 `lxml` 解析网页、使用 XPath 语法、使用正则表达式进行信息提取以及使用 `Selenium` 或 `Pyppeteer` 处理动态网页。 ### 三、使用 BeautifulSoup4 或 lxml 解析网页 `BeautifulSoup4` 和 `lxml` 是两个常用的 HTML/XML 解析器库,可以帮助开发者从网页中提取所需的信息。 **1. 使用 BeautifulSoup4** 首先安装 `beautifulsoup4` 和 `lxml`: ```bash pip install beautifulsoup4 lxml ``` 然后可以这样使用: ```python from bs4 import BeautifulSoup import requests url = 'https://www.example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'lxml') # 提取所有链接 links = [link['href'] for link in soup.find_all('a') if 'href' in link.attrs] print(links) ``` **2. 使用 lxml** `lxml` 是一个强大的 XML/HTML 解析器库,它可以解析不规范的 HTML 文档: ```python from lxml import etree import requests url = 'https://www.example.com' response = requests.get(url) html = etree.HTML(response.text) # 提取所有链接 links = html.xpath('//a/@href') print(links) ``` ### 四、使用 XPath 语法 XPath 是一种在 XML 文档中查找信息的语言,同样适用于 HTML。使用 XPath 可以精确地定位文档中的元素。 ```python from lxml import etree import requests url = 'https://www.example.com' response = requests.get(url) html = etree.HTML(response.text) # 提取特定元素 title = html.xpath('//title/text()')[0] print(title) ``` ### 五、使用正则表达式进行信息提取 正则表达式是一种强大的文本匹配工具,可以用来从非结构化的文本中提取特定模式的数据。 ```python import re import requests url = 'https://www.example.com' response = requests.get(url) content = response.text # 提取电子邮件地址 emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', content) print(emails) ``` ### 六、使用 Selenium 或 Pyppeteer 处理动态网页 对于那些通过 JavaScript 动态加载内容的网页,传统的爬虫技术可能无法完全获取页面内容。这时可以考虑使用 `Selenium` 或 `Pyppeteer` 这样的自动化测试工具。 **1. 使用 Selenium** 首先安装 `selenium` 和相应的 WebDriver(例如 ChromeDriver): ```bash pip install selenium ``` 然后可以这样使用: ```python from selenium import webdriver driver = webdriver.Chrome('/path/to/chromedriver') driver.get('https://www.example.com') # 交互操作 element = driver.find_element_by_id('some_id') element.click() # 获取页面源代码 html = driver.page_source driver.quit() ``` **2. 使用 Pyppeteer** `Pyppeteer` 是一个 Node.js 库,可以用来控制 Chrome 或 Chromium 浏览器,从而实现无头浏览器的功能。 首先安装 `pyppeteer`: ```bash npm install pyppeteer ``` 然后可以这样使用: ```python import asyncio from pyppeteer import launch async def main(): browser = await launch() page = await browser.newPage() await page.goto('https://www.example.com') # 交互操作 await page.click('#some_id') # 获取页面源代码 html = await page.content() await browser.close() print(html) asyncio.run(main()) ``` ### 结论 本文介绍了几种常见的基础 Python 爬虫方法,包括使用 `urllib` 和 `requests` 进行网络请求、使用 `BeautifulSoup4` 和 `lxml` 解析 HTML/XML 文档、使用 XPath 和正则表达式提取信息,以及使用 `Selenium` 和 `Pyppeteer` 处理动态网页。每种方法都有其特点和适用场景,开发者可以根据具体的需求选择合适的技术栈。
























剩余12页未读,继续阅读


- 粉丝: 4654
- 资源: 819
我的内容管理 展开
我的资源 快来上传第一个资源
我的收益
登录查看自己的收益我的积分 登录查看自己的积分
我的C币 登录后查看C币余额
我的收藏
我的下载
下载帮助


最新资源
- 毕业设计-昆虫识别和数目统计系统源码+LW.zip
- 基于Matlab的心电信号ECG去噪处理:结合低通滤波与小波分解去高频噪声、工频干扰及基线漂移解决方案,基于Matlab的心电信号ECG去噪处理:结合低通滤波与小波分解,消除高频噪声、工频干扰及基线漂
- 超轻量级图像中文识别组件 chineseocr_lite 的 DLL 版本(用于 aardio 扩展库,适用于任何支持DLL的语言).zip
- 车牌识别,FPGA,2019全国大学生集成电路创新创业大赛.zip
- 从网易云音乐、QQ音乐等在线音乐平台获取歌单转换成椒盐音乐可识别的歌单格式(方便用户快速跨平台迁移歌单).zip
- 基于Vue框架的校园论坛Web前端设计源码
- 第三届中国软件杯决赛视频分析系统赛题(基于vc++,opencv,svm等算法对视频中的车牌进行定位和识别).zip
- 车牌识别停车计费系统新版源码+说明.zip
- 基于comsol技术的金层二氧化硅SPR传感器的研究与应用,基于COMSOL的金层二氧化硅SPR传感器模拟与性能研究,comsol金层二氧化硅SPR传感器 ,comsol; 金层; 二氧化硅; SPR
- 电子发票识别项目新版源码(可识别电子普票+电子专票).zip
- 点选式验证码识别方案源码.zip
- 电脑QQ截图工具提取版(支持文字提取、图片识别、截长图、qq录屏+默认截图文件名为ScreenShot日期).zip
- 对目标域名进行快速的存活扫描、简单的指纹识别、目录扫描项目源码.zip
- 端到端中文语音识别源码.zip
- 抖音的Autojs人脸识别脚本.zip
- 二维码_条形码扫描、生成_识别工具(仿微信、支付宝).zip


