网络爬虫:网络爬虫函数-使用Python进行网页抓取和数据提取
发布时间:2023-07-04 17:35:45
网络爬虫是一种自动化程序,它能够从互联网上抓取网页并提取其中的信息。在这里我们将介绍使用Python编写网络爬虫的常用函数。
首先,我们需要导入一些库。requests库是用于发送HTTP请求的库,beautifulsoup库用于解析HTML页面,re库用于处理正则表达式。
import requests from bs4 import BeautifulSoup import re
然后,我们可以定义一个函数来发送HTTP请求并获取网页内容。
def get_html(url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0;Win64) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
response = requests.get(url, headers=headers)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except Exception as e:
print('请求网页出现异常:', e)
return None
接下来,我们可以定义一个函数来解析HTML页面并提取我们需要的数据。
def parse_html(html):
try:
soup = BeautifulSoup(html, 'html.parser')
# 使用soup对象的find_all方法来查找所有符合条件的标签
# 然后使用get_text()方法来获取标签的文本内容
data = soup.find_all('a', href=re.compile(r'^http://www\.example\.com/.*$'))
for item in data:
print(item.get_text())
except Exception as e:
print('解析网页出现异常:', e)
最后,我们可以编写一个主函数来组织整个爬虫的流程。
def main():
url = 'http://www.example.com/'
html = get_html(url)
if html:
parse_html(html)
通过调用主函数,我们就可以开始抓取网页并提取数据了。
if __name__ == '__main__':
main()
这些函数只是网络爬虫中的一小部分,网络爬虫的功能可以扩展到更复杂的任务,比如登录、图片下载等。但这些函数提供了一个入门级的网络爬虫框架,可以帮助我们获取网页并提取其中的数据。
