登录网站,然后在浏览器中打开

时间:2019-07-20 19:14:02

标签: python-3.x request urllib

我正在尝试编写一个Python 3代码,该代码登录到一个网站,然后在网络浏览器中打开它以获取其屏幕截图。 在网上寻找,我发现我可以做webbrowser.open('example.com') 这将打开网站,但无法登录。 然后,我发现可以使用请求库或urllib登录网站。 但是两者的问题在于它们似乎没有提供打开网页的选项。

那么如何登录到网页然后显示它,以便可以截取该页面的屏幕截图

谢谢

1 个答案:

答案 0 :(得分:0)

您是否考虑过Selenium?它像用户本机一样驱动浏览器,其Python客户端非常易于使用。

这是我与Selenium合作的最新作品之一。这是一个脚本,可从某个网站抓取多个页面并将其数据保存到csv文件中:

import os
import time
import csv

from selenium import webdriver

cols = [
    'ies', 'campus', 'curso', 'grau_turno', 'modalidade',
    'classificacao', 'nome', 'inscricao', 'nota'
]

codigos = [
    96518, 96519, 96520, 96521, 96522, 96523, 96524, 96525, 96527, 96528
]

if not os.path.exists('arquivos_csv'):
    os.makedirs('arquivos_csv')

options = webdriver.ChromeOptions()
prefs = {
    'profile.default_content_setting_values.automatic_downloads': 1,
    'profile.managed_default_content_settings.images': 2
}
options.add_experimental_option('prefs', prefs)

# Here you choose a webdriver ("the browser")
browser = webdriver.Chrome('chromedriver', chrome_options=options)

for codigo in codigos:
    time.sleep(0.1)
    # Here is where I set the URL
    browser.get(f'http://www.sisu.mec.gov.br/selecionados?co_oferta={codigo}')
    with open(f'arquivos_csv/sisu_resultados_usp_final.csv', 'a') as file:
        dw = csv.DictWriter(file, fieldnames=cols, lineterminator='\n')
        dw.writeheader()
        ies = browser.find_element_by_xpath('//div[@class ="nome_ies_p"]').text.strip()
        campus = browser.find_element_by_xpath('//div[@class ="nome_campus_p"]').text.strip()
        curso = browser.find_element_by_xpath('//div[@class ="nome_curso_p"]').text.strip()
        grau_turno = browser.find_element_by_xpath('//div[@class = "grau_turno_p"]').text.strip()
        tabelas = browser.find_elements_by_xpath('//table[@class = "resultado_selecionados"]')
        for t in tabelas:
            modalidade = t.find_element_by_xpath('tbody//tr//th[@colspan = "4"]').text.strip()
            aprovados = t.find_elements_by_xpath('tbody//tr')
            for a in aprovados[2:]:
                linha = a.find_elements_by_class_name('no_candidato')
                classificacao = linha[0].text.strip()
                nome = linha[1].text.strip()
                inscricao = linha[2].text.strip()
                nota = linha[3].text.strip().replace(',', '.')
                dw.writerow({
                    'ies': ies, 'campus': campus, 'curso': curso,
                    'grau_turno': grau_turno, 'modalidade': modalidade,
                    'classificacao': classificacao, 'nome': nome,
                    'inscricao': inscricao, 'nota': nota
                })

browser.quit()

简而言之,您可以设置首选项,选择一个网络驱动程序(我建议使用Chrome),指向URL,仅此而已。浏览器将自动打开并开始执行您的指令。

我已经测试过使用它登录,并且可以正常工作,但是从未尝试过截屏。理论上应该可以。

相关问题