网络爬虫是一种自动化程序,通过发送HTTP请求并解析HTML等网页内容,获取指定网页数据的工具。下面是一个简单的Python代码示例,用于实现一个基本的网络爬虫:
import requests
from bs4 import BeautifulSoup
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except:
return ""
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
# 在这里可以使用BeautifulSoup提供的各种方法解析网页内容,并获取需要的数据
# 例如,使用soup.find_all()方法获取所有的链接<a>标签
# 使用soup.select()方法获取指定CSS选择器的内容
# 使用soup.get_text()方法获取网页中的纯文本内容
# etc.
# 具体使用方法可参考BeautifulSoup的官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc/
def crawl(url):
html = get_html(url)
parse_html(html)
if __name__ == "__main__":
url = "https://example.com" # 指定要爬取的网页URL
crawl(url)
这段代码通过requests
库发送HTTP请求,获取网页内容;通过BeautifulSoup
库解析HTML,获取指定的数据。你可以根据需要对代码进行修改和扩展,以适应具体的爬取需求。