参考教材实例20,编写Python爬虫程序,爬取地址: https://www.luogu.com.cn/contest/68651#scoreboard中的比赛榜单, 读取《用户信息.xls文件》,如果用户信息中的账号不在榜单中则排名填-1,如果用户在榜单中则爬取用户的排名和题目通过情况(例:A题通过则填AC,否则留空)
时间: 2024-02-29 17:55:10 浏览: 29
好的,我能理解您的要求。由于这是一个比较复杂的任务,需要爬取网页、读取 Excel 文件、处理数据等多个步骤,我会分步骤给出代码实现。首先我们需要安装一些必要的库:
```
pip install openpyxl requests beautifulsoup4
```
接下来,我们先读取 Excel 文件中的用户信息。这里我假设用户信息保存在 `users.xlsx` 文件中,第一列为账号,第二列为姓名,代码如下:
```python
import openpyxl
# 读取用户信息
users = {}
wb = openpyxl.load_workbook('users.xlsx')
ws = wb.active
for row in ws.iter_rows(min_row=2, values_only=True):
account, name = row
users[account] = {'name': name, 'rank': -1, 'problems': {}}
```
接下来,我们需要爬取比赛榜单页面,从中获取用户的排名和通过情况。这里我使用 `requests` 库来获取网页内容,`beautifulsoup4` 库来解析 HTML,代码如下:
```python
import requests
from bs4 import BeautifulSoup
# 爬取比赛榜单
url = 'https://www.luogu.com.cn/contest/68651'
resp = requests.get(f'{url}/scoreboard')
soup = BeautifulSoup(resp.text, 'html.parser')
# 解析排名信息
for tr in soup.select('.lg-table > tbody > tr'):
account = tr.select_one('.lg-right > a').text
if account in users:
rank = tr.select_one('.lg-right:nth-child(2)').text
users[account]['rank'] = rank
for td in tr.select('td.lg-right-td')[2:]:
if td.text.strip() == '-':
users[account]['problems'][td['data-problem-id']] = ''
else:
users[account]['problems'][td['data-problem-id']] = td.text.strip()
```
最后,我们可以将结果写入 Excel 文件中。这里我将结果保存在 `result.xlsx` 文件中,第一列为账号,第二列为姓名,第三列为排名,第四列到第 N+3 列为每个题目的通过情况,N 为题目数量,代码如下:
```python
# 写入结果
wb = openpyxl.Workbook()
ws = wb.active
ws.append(['账号', '姓名', '排名'] + [f'题目{i}' for i in range(1, len(users[next(iter(users))]['problems']) + 1)])
for account, info in users.items():
row = [account, info['name'], info['rank']]
for problem in info['problems'].values():
row.append(problem)
ws.append(row)
wb.save('result.xlsx')
```
完整代码如下所示: