Selenium - ссылка на веб-элемент, которую раньше не видели - PullRequest
0 голосов
/ 06 мая 2020

Итак, я пытаюсь создать веб-скребок, который обнаруживает каждый каталог по этой ссылке: https://coursevania.courses.workers.dev/ [coursevania.com] Python% 20for% 20Data% 20Science% 20and% 20Machine% 20Learning% 20Bootcamp /

, а затем в каждом каталоге, чтобы получить имя каждого файла в самом каталоге и вернуться на главную страницу, я использовал довольно неэффективный подход, есть ли лучший способ сделать это с помощью селена?

from selenium import webdriver
import time
from bs4 import BeautifulSoup
import requests


# Step 1: Print all the names of every file in the directory
def mainpage():
    browser.back()
    browser.back()

browser = webdriver.Firefox()
browser.get(r"https://coursevania.courses.workers.dev/[coursevania.com]Python%20for%20Data%20Science%20and%20Machine%20Learning%20Bootcamp/")
time.sleep(2)
elements = browser.find_elements_by_css_selector(".mdui-text-truncate")
for i in range(len(elements)):
    browser.get(r"https://coursevania.courses.workers.dev/[coursevania.com]Python%20for%20Data%20Science%20and%20Machine%20Learning%20Bootcamp/")
    time.sleep(2)
    elements = browser.find_elements_by_css_selector(".mdui-text-truncate")
    element = elements[i]
    print(element.text[11:].strip(" ."), "------------------------------", sep="\n")
    time.sleep(2)
    element.click()
    time.sleep(2)
    files = browser.find_elements_by_css_selector(".mdui-text-truncate")
    for _file in files:
        print(_file.text[17:].strip())
    print("------------------------------", "", sep="\n")
    mainpage()
    time.sleep(4)

Формат вывода следующий:

Directory Name
------------------------------
filename1
filename2
filename3
...
filenamenth
------------------------------

Directory Name
------------------------------
...
------------------------------

1 Ответ

0 голосов
/ 06 мая 2020

Ну, сообщения запроса возвращают формат json, который вы можете использовать для итерации и распечатки имен. Не уверен, что именно вы хотите, но вы можете следовать этому:

import requests
import urllib.parse

url = 'https://coursevania.courses.workers.dev/[coursevania.com]Python%20for%20Data%20Science%20and%20Machine%20Learning%20Bootcamp/'

jsonData = requests.post(url).json()

files = jsonData['files']
output = {}
for each in files:
    directory = each['name']
    print (directory)
    print("------------------------------")
    output[directory] = []
    root = 'https://coursevania.courses.workers.dev/[coursevania.com]Python%20for%20Data%20Science%20and%20Machine%20Learning%20Bootcamp/'
    linkParse = urllib.parse.quote(directory)

    link = root + linkParse + '/'
    jsonData = requests.post(link).json()


    for file in jsonData['files']:
        fileName = file['name']
        print (fileName)
        if fileName not in output[directory]:
            output[directory].append(fileName)
    print("------------------------------", "", sep="\n")


print (output)

Вывод:

1. Course Introduction
------------------------------
1. Introduction to the Course.mp4
1. Introduction to the Course.vtt
2. Course Help and Welcome.mp4
2. Course Help and Welcome.vtt
3. Course FAQs.html
3.1 Py_DS_ML_Bootcamp-master.zip.zip
------------------------------

10. Python for Data Visualization - Pandas Built-in Data Visualization
------------------------------
1. Pandas Built-in Data Visualization.mp4
1. Pandas Built-in Data Visualization.vtt
2. Pandas Data Visualization Exercise.mp4
2. Pandas Data Visualization Exercise.vtt
3. Pandas Data Visualization Exercise- Solutions.mp4
3. Pandas Data Visualization Exercise- Solutions.vtt
------------------------------

11. Python for Data Visualization - Plotly and Cufflinks
------------------------------
1. Introduction to Plotly and Cufflinks.mp4
1. Introduction to Plotly and Cufflinks.vtt
2. Plotly and Cufflinks.mp4
2. Plotly and Cufflinks.vtt
------------------------------

12. Python for Data Visualization - Geographical Plotting
------------------------------
1. Introduction to Geographical Plotting.mp4
1. Introduction to Geographical Plotting.vtt
2. Choropleth Maps - Part 1 - USA.mp4
2. Choropleth Maps - Part 1 - USA.vtt
3. Choropleth Maps - Part 2 - World.mp4
3. Choropleth Maps - Part 2 - World.vtt
4. Choropleth Exercises.mp4
4. Choropleth Exercises.vtt
5. Choropleth Exercises - Solutions.mp4
5. Choropleth Exercises - Solutions.vtt
------------------------------
....
...