用Python爬取大乐透指定期数开奖结果
时间: 2024-02-16 21:53:26 浏览: 41
可以使用Python的requests和BeautifulSoup库来爬取大乐透指定期数的开奖结果。以下是一个简单的爬取示例:
```python
import requests
from bs4 import BeautifulSoup
# 指定要爬取的大乐透期数
period = '2021022'
# 构造请求URL
url = 'http://www.lottery.gov.cn/historykj/history.jspx?_ltype=dlt&_term=' + period
# 发送请求并解析HTML
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 找到开奖结果所在的表格
table = soup.find('table', {'class': 'kj_tablelist02'})
# 解析开奖结果
result = []
for row in table.find_all('tr')[1:]:
nums = [int(td.text.strip()) for td in row.find_all('td')[1:]]
result.append(nums)
print('大乐透第%s期开奖结果为:%s' % (period, result))
```
在上面的代码中,我们首先指定要爬取的大乐透期数,然后构造请求URL并发送请求。接着,我们使用BeautifulSoup库解析HTML并找到开奖结果所在的表格。最后,我们解析表格中的每一行数据,获得大乐透的开奖结果。
需要注意的是,以上代码仅供学习参考,爬虫行为可能违反相关规定,请勿用于非法用途。