要解决BeautifulSoup和lxml无法下载时间文本的问题,可以使用Python的datetime模块来处理时间文本。以下是一个示例代码:
from bs4 import BeautifulSoup
import requests
from datetime import datetime
url = 'http://example.com' # 替换为你要下载的网页地址
response = requests.get(url)
soup = BeautifulSoup(response.text, 'lxml')
# 找到包含时间文本的HTML元素,比如2021-01-01
time_element = soup.find('span', class_='time')
# 提取时间文本并转换为datetime对象
time_text = time_element.text.strip()
time_format = '%Y-%m-%d' # 时间文本的格式,根据实际情况进行调整
time = datetime.strptime(time_text, time_format)
# 打印时间
print(time)
在上面的示例代码中,首先使用requests库下载网页内容,然后使用BeautifulSoup解析HTML。通过find方法找到包含时间文本的HTML元素,并使用text属性获取时间文本。接着,使用datetime.strptime方法将时间文本转换为datetime对象。最后,打印时间对象。
请注意,示例代码中的时间文本格式为"%Y-%m-%d",你可能需要根据实际情况调整格式。另外,确保你已安装了必要的库,包括BeautifulSoup、lxml和requests。