python 爬虫 代码
pythonimport requests
from bs4 import BeautifulSoup
def fetch_html(url):
try:
response = requests.get(url)
response.raise_for_status() # 检查请求是否成功
return response.text
except requests.RequestException as e:
print("请求失败:", e)
return None
def parse_html(html):
if html is None:
return None
soup = BeautifulSoup(html, 'html.parser')
# 这里以获取标题为例,你可以根据需要解析其他内容
title = soup.title.string
return title
def main():
url = 'https://example.com' # 替换为你要爬取的网页链接
html = fetch_html(url)
if html:
data = parse_html(html)
print("网页标题:", data)
if __name__ == "__main__":
main()
在这个示例中,我们使用了 requests 库来获取网页内容,并使用 BeautifulSoup 库来解析 HTML。你可以根据需要修改 parse_html 函数来解析网页中的不同部分。记得替换 url 变量为你要爬取的网页链接。同时,注意合理使用爬虫,
添加异常处理,处理可能的网络请求异常和解析异常。添加一些随机延迟,以避免给网站造成过大的访问压力。将爬取到的数据保存到文件或者数据库中,以便后续处理或者分析。
pythonimport requests
from bs4 import BeautifulSoup
import time
import random
def fetch_html(url):
try:
response = requests.get(url)
response.raise_for_status() # 检查请求是否成功
return response.text
except requests.RequestException as e:
print("请求失败:", e)
return None
def parse_html(html):
if html is None:
return None
try:
soup = BeautifulSoup(html, 'html.parser')
# 这里以获取标题为例,你可以根据需要解析其他内容
title = soup.title.string
return title
except Exception as e:
print("解析失败:", e)
return None
def save_data(data, filename):
with open(filename, 'a', encoding='utf-8') as f:
f.write(data + '\n')
def main():
urls = ['https://example.com/page1', 'https://example.com/page2'] # 替换为你要爬取的网页链接列表
for url in urls:
html = fetch_html(url)
if html:
data = parse_html(html)
if data:
print("成功爬取数据:", data)
save_data(data, 'data.txt') # 将数据保存到文件中
else:
print("解析失败,跳过此页面:", url)
else:
print("请求失败,跳过此页面:", url)
# 随机延迟一段时间
time.sleep(random.uniform(1, 3))
if __name__ == "__main__":
main()
这个示例中,我添加了保存数据的功能,并且可以处理请求失败和解析失败的情况。同时,为了避免对目标网站造成过大的访问压力,我在每次请求之后都添加了一个随机的延迟时间。