1、免费题目爬取-selenium方式
1.1 实现流程
- 设置Chrome驱动
- 配置参数,解决下载文件的安全提示
- 登录网页
- 点击下载按钮
1.2 运行流程
输入验证码
下载文件
解除Chrome安全文件下载提示
Chrome默认会对下载的文件做安全检测,但是在使用selenium自动下载时我们先禁止扫描,实现自动下载
禁用安全扫描代码
driver = webdriver.Chrome('chromedriver.exe',) # 谷歌浏览器
# 取消chrome下载文件的安全提示
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior',
'params': {'behavior': 'allow', 'downloadPath': r'C:\Users\RION\Desktop\test'}} # downloadPath : 指定下载路径
driver.execute("send_command", params)
1.3 总代码
import time
from selenium import webdriver
def login(username,password):
driver = webdriver.Chrome('chromedriver.exe',) # 谷歌浏览器
# 取消chrome下载文件的安全提示
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior',
'params': {'behavior': 'allow', 'downloadPath': r'C:\Users\RION\Desktop\test'}} # downloadPath : 指定下载路径
driver.execute("send_command", params)
# 打开网址,输入用户名和密码
driver.get('http://tk.hustoj.com/loginpage.php')
driver.find_element_by_name('user_id').send_keys(username)
driver.find_element_by_name('password').send_keys(password)
# 手动输入验证码
vcode = input('请输入验证码: ')
driver.find_element_by_name('vcode').send_keys(vcode)
driver.find_element_by_name('submit').click()
# 下载免费专区 - xml文件下载
driver.get('http://tk.hustoj.com/problemset.php?search=free')
time.sleep(2)
file_xml = driver.find_elements_by_css_selector('#problemset > tbody > tr > td:nth-child(7) > div > span > a:nth-child(1)')
for file in file_xml:
try:
file.click()
except Exception as e:
continue # 异常跳过下载下一个文件
if __name__ == '__main__':
username = '账户名称' # 用户名
password = '账户密码' # 密码
try:
driver = login(username,password)
except Exception as e:
print(e)
2、某网题目爬取-requests方式保存Excel
2.1 实现流程
- 打开网址
- 解析网页
- 获取内容
- 保存Excel
保存标签下的所有文本
content = tree.xpath('//*[@class="content"]')
data.append({'id':i,'title_desc':content[0].xpath('string(.)').strip()})
2.2 运行结果
2.3 总代码
import requests
from lxml import etree
import pandas as pd
def get_content():
url = "http://tk.hustoj.com/problem.php?id={}"
data = []
for i in range(1000,2000):
new_url = url.format(i)
print('ID={} 打开网址: {}'.format(i,new_url))
response = requests.get(url=new_url).text
tree = etree.HTML(response)
content = tree.xpath('//*[@class="content"]')
try:
data.append({'id':i,'title_desc':content[0].xpath('string(.)').strip(),'input':content[1].xpath('string(.)').strip(),'ouput':content[2].xpath('string(.)').strip(),'exp_input':content[3].xpath('string(.)').strip(),'exp_output':content[4].xpath('string(.)').strip(),'source':content[6].xpath('string(.)').strip()})
except Exception as e:
continue
return data
def save_excel(data):
writer = pd.ExcelWriter('./tiku.xlsx') # 创建Excel
pf = pd.DataFrame(data) # 定义格式
pf.to_excel(writer, index=False, encoding='utf-8') # 写入Excel
writer.save()
if __name__ == '__main__':
data = get_content()
save_excel(data)
文章若有写错的地方欢迎大佬指正。谢谢!