Я следовал руководству по веб-очистке веб-страницы http://kanview.ks.gov/PayRates/PayRates_Agency.aspx. Турориал можно найти здесь: https://medium.freecodecamp.org/better-web-scraping-in-python-with-selenium-beautiful-soup-and-pandas-d6390592e251. Макет похож на веб-сайт, который я хочу просмотретьинформация: https://www.giiresearch.com/topics/TL11.shtml. Моя единственная проблема заключается в том, что ссылки на веб-сайте giiresearch для заголовков отчетов не следуют в хронологическом порядке, например.ниже приведены данные исследования gii
a href="/report/an806147-fixed-mobile-convergence-from-challenger-operators.html">Fixed-Mobile Convergence from Challenger Operators: Case Studies and Analysis</a>
a href="/annual/an378138-convergence-strategies.html">Convergence Strategies</a>
Ссылки на веб-сайте kanview следуют порядку, например.
a id="MainContent_uxLevel2_JobTitles_uxJobTitleBtn_1" href="javascript:__doPostBack('ctl00$MainContent$uxLevel2_JobTitles$ctl03$uxJobTitleBtn','')">Academic Advisor</a
a id="MainContent_uxLevel2_JobTitles_uxJobTitleBtn_2" href="javascript:__doPostBack('ctl00$MainContent$uxLevel2_JobTitles$ctl04$uxJobTitleBtn','')">Academic Program Specialist</a>
Это означает, что я не могу использовать метод, использованный в их строке кода для моего проекта:
python_button = driver.find_element_by_id('MainContent_uxLevel2_JobTitles_uxJobTitleBtn_' + str(x))
Я пытался найти find_elements_by_class_name, но все ссылки имеют одинаковый классимя «списка заголовков», поэтому цикл for открывает только первую ссылку и не идет дальше.
Я подумал, что должен быть способ сохранить ссылки на заголовок отчета в списке, чтобы я могможно открыть их один за другим, чтобы получить больше информации о каждом отчете и сохранить его в листе Excel.
Это проект, в котором я хочу составить лист отчетов конкурентов Excel со статистикой по их названиям, цене,издатель, дата публикации и т. д. для анализа рынка.
Вот мой код:
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import re
import pandas as pd
from tabulate import tabulate
import os
#launch url
url = "https://www.giiresearch.com/topics/TL11.shtml"
# create a new Chrome session
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(30)
driver.get(url)
#Selenium hands the page source to Beautiful Soup
soup_level1=BeautifulSoup(driver.page_source, 'lxml')
datalist = [] #empty list
x = 0 #counter
#Beautiful Soup finds all Job Title links on the agency page and the loop begins
for link in soup_level1.find_all("div", {"class": "list_title"}):
#Selenium visits each Job Title page
python_button = driver.find_elements_by_class_name('list_title')
python_button.click() #click link
#Selenium hands of the source of the specific job page to Beautiful Soup
soup_level2=BeautifulSoup(driver.page_source, 'lxml')
#Beautiful Soup grabs the HTML table on the page
table = soup_level2.find_all('table')[0]
#Giving the HTML table to pandas to put in a dataframe object
df = pd.read_html(str(table),header=0)
#Store the dataframe in a list
datalist.append(df[0])
#Ask Selenium to click the back button
driver.execute_script("window.history.go(-1)")
#increment the counter variable before starting the loop over
x += 1
#end loop block
#loop has completed
#end the Selenium browser session
driver.quit()
#combine all pandas dataframes in the list into one big dataframe
result = pd.concat([pd.DataFrame(datalist[i]) for i in range(len(datalist))],ignore_index=True)
#convert the pandas dataframe to JSON
json_records = result.to_json(orient='records')
#pretty print to CLI with tabulate
#converts to an ascii table
print(tabulate(result, headers=["Report Title","Publisher","Published Date","Price"],tablefmt='psql'))
#get current working directory
path = os.getcwd()
#open, write, and close the file
f = open(path + "\\fhsu_payroll_data.json","w") #FHSU
f.write(json_records)
f.close()