在Python爬蟲中,使用urllib庫進行網頁抓取后,通常需要對抓取到的數據進行清洗。數據清洗的目的是去除不需要的字符、格式化數據、提取有用信息等。以下是一些建議的步驟:
import urllib.request
import re
url = 'https://example.com'
response = urllib.request.urlopen(url)
html = response.read().decode('utf-8')
re
庫進行正則表達式操作。例如,假設我們需要從抓取的HTML內容中提取所有的電子郵件地址:
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
emails = re.findall(email_pattern, html)
去除空值:
cleaned_emails = [email for email in emails if email]
去除重復值:
unique_emails = list(set(cleaned_emails))
格式化日期:
假設我們需要將抓取到的日期字符串轉換為YYYY-MM-DD
格式:
date_pattern = r'\b\d{4}-\d{2}-\d{2}\b'
dates = re.findall(date_pattern, html)
formatted_dates = []
for date in dates:
day, month, year = map(int, date.split('-'))
formatted_dates.append(f'{year}-{month:02d}-{day:02d}')
with open('cleaned_data.txt', 'w') as f:
for item in unique_emails + formatted_dates:
f.write(item + '\n')
以上示例展示了如何使用urllib庫抓取網頁內容,并使用正則表達式進行數據清洗。根據實際需求,可以調整正則表達式和清洗步驟。