Как я могу просмотреть список веб-сайтов (из файла Excel), чтобы получить ценность с каждого сайта с помощью Python Selenium?
Например, столбец в файле Excel содержит:
https://www.inc.com/profile/dom-&-tom
https://www.inc.com/profile/decksouth
https://www.inc.com/profile/shp-financial
and many more.....
Я хочу получить конкретный атрибут HREF из каждой ссылки.
Мой код:
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("https://www.inc.com/profile/bluestone-staffing")
website_link_anchor =
browser.find_element_by_xpath("//dd[@class='website']/a")
actual_website_link = website_link_anchor.get_attribute("href")
print(actual_website_link)
browser.get("https://www.inc.com/profile/homecity-real-estate")
website_link_anchor =
browser.find_element_by_xpath("//dd[@class='website']/a")
actual_website_link = website_link_anchor.get_attribute("href")
print(actual_website_link)
browser.close()
Любой вход был бы высоко оценен.
Любые предложения по улучшению моего кода?
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
import xlrd
import xlwt
from xlutils.copy import copy
def scraping(browser, link):
returnValue = ""
browser.get(link)
try:
website_link_anchor = browser.find_element_by_xpath("//dd[@class='website']/a")
actual_website_link = website_link_anchor.get_attribute("href")
returnValue = actual_website_link
except NoSuchElementException:
returnValue = "Element not found for: " + link
return returnValue
options = Options()
options.add_argument("--headless")
browser = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
file_to_read = ("C:\INC5000\list.xlsx")
# read
file_to_read_wb = xlrd.open_workbook(file_to_read)
file_to_read_wb_sheet = file_to_read_wb.sheet_by_index(0)
# copy and write
file_to_write_to_wb = copy(file_to_read_wb)
file_to_write_to_wb_sheet = file_to_write_to_wb.get_sheet(0)
for i in range(1, file_to_read_wb_sheet.nrows):
result = scraping(browser, file_to_read_wb_sheet.cell_value(i, 0))
file_to_write_to_wb_sheet.write(i, 1, result)
file_to_write_to_wb.save("C:\INC5000\list2.xls")
browser.close()
Чтобы просмотреть список веб-сайтов (из файла Excel) и получить значение с каждого веб-сайта, вам необходимо:
driver.quit()
в tearDown(){}
чтобы изящно закрыть и уничтожить экземпляры WebDriver и Web Client.Ваш пример кода будет:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
myLinks = ['https://www.inc.com/profile/dom-&-tom', 'https://www.inc.com/profile/decksouth', 'https://www.inc.com/profile/shp-financial']
options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
browser = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
for link in myLinks:
browser.get(link)
website_link_anchor = browser.find_element_by_xpath("//dd[@class='website']/a")
actual_website_link = website_link_anchor.get_attribute("href")
print(actual_website_link)
browser.quit()
читать excel использовать библиотеку xlrd
. В sheet.cell_value(i, 0)
здесь i
- индекс row
а 0
- индекс столбца. измените индекс столбца в соответствии с вашими данными Excel.
определенную функцию для слома и возвращаемого значения или при необходимости добавьте ее в другой список. в вашем случае вы просто печатаете, поэтому я возвращаю None
import xlrd
from selenium import webdriver
# Give the location of the file
def scrapping(browser, links):
browser.get(links)
website_link_anchor = browser.find_element_by_xpath("//dd[@class='website']/a")
actual_website_link = website_link_anchor.get_attribute("href")
print(actual_website_link)
return None
driver = webdriver.Chrome()
loc = ("path of file")
# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
# links = []
for i in range(1, sheet.nrows):
scrapping(driver, sheet.cell_value(i, 0))
# links.append(sheet.cell_value(i, 0))
driver.close()