网络爬虫是一种自动化程序,其主要作用在于系统地获取互联网上的网页内容,并从中提取有用数据。爬虫工作的基本目标为从给定的起始 URL 着手,以递归方式获取页面上链接的网页,并依据规则提取相应信息。
爬虫的工作流程
选择种子URL:确定开始的网页地址。
发送HTTP请求:使用requests库或类似工具发送请求获取网页内容。
解析网页数据:使用BeautifulSoup或lxml解析并提取数据。
存储数据:将提取的信息存储到数据库、文件等。
发现新链接:从当前页面中找到新的链接并重复步骤。
常用的爬虫工具和库
Requests:用于发送HTTP请求。
BeautifulSoup:一个流行的HTML解析库。
Scrapy:一个用于编写爬虫的框架,功能强大。
Selenium:用于模拟浏览器行为,适合动态内容加载。
代码示例与函数设置
下面是使用requests和BeautifulSoup实现简单爬虫的代码示例:
————————————————
import requests
from bs4 import BeautifulSoup
# 指定请求头,以模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 发送GET请求
def fetch_html(url):
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 如果响应状态码不是200,会引发HTTPError
return response.text
except requests.exceptions.HTTPError as http_err:
print(f'HTTP error occurred: {http_err}') # HTTP错误
except Exception as err:
print(f'Other error occurred: {err}') # 其他错误
# 解析HTML
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
# 提取页面标题作为示例
title = soup.title.string if soup.title else 'No Title Found'
print(f'Page title: {title}')
# 提取所有链接
links = [a['href'] for a in soup.find_all('a', href=True)]
return links
# 运行示例爬虫
if __name__ == "__main__":
url = "https://example.com"
html_content = fetch_html(url)
if html_content:
links = parse_html(html_content)
print(f'Found {len(links)} links on this page.')
函数参数设置
headers:模拟浏览器访问,可以避免被某些网站屏蔽。User-Agent是最常设置的请求头。
requests.get(url, headers=headers):get()函数用于发送GET请求。常用参数包括:
params: 字典或字节流,用于请求的查询参数部分。
headers: 字典,指定HTTP请求头信息。
timeout: 超时时间,浮点数秒。
response.raise_for_status():用于抛出HTTP错误异常,确保程序能够处理出现的错误。
常见问题及解决方案
- 动态内容加载
问题:一些网站使用JavaScript动态加载内容,requests库无法抓取。
解决方案:使用Selenium模拟浏览器加载,获取动态内容。
from selenium import webdriver
# 使用Chrome浏览器驱动
driver = webdriver.Chrome()
# 打开网页
driver.get("https://example.com")
# 等待几秒钟以便页面加载
driver.implicitly_wait(10)
# 获取动态加载的内容
dynamic_content = driver.find_element_by_css_selector("div.content").text
print(dynamic_content)
driver.quit()
2.反爬虫机制问题:网站启用机制来检测并阻拦爬虫,像验证码、人机验证之类的。解决方案:不妨试着调整一下请求的频率,运用代理 IP,或者在合法的情形下通过人工或者算法来处理验证码。
3.数据存储问题:怎样高效地存储和管理爬取到的大量数据呢?解决方案:采用数据库(例如 MySQL、MongoDB)或者大数据平台来进行存储。