【发布时间】:2020-11-29 04:31:09
【问题描述】:
您好,我是数据抓取的新手。在这里,我试图从具有 'heading' 属性的所有类中抓取数据。但在我的代码中,即使我使用 for 循环进行迭代,它也只打印第一个元素。
预期输出 - 从所有具有属性 'heading'
的页面类中抓取数据实际输出 - 仅从类名为“标题”的第一个元素中抓取数据,甚至不点击下一步按钮。
我用于测试的网站是here
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import pandas as pd
from openpyxl.workbook import Workbook
DRIVER_PATH = 'C:/Users/Aishwary/Downloads/chromedriver_win32/chromedriver'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get('https://www.fundoodata.com/citiesindustry/19/2/list-of-information-technology-(it)-companies-in-noida')
# get all classes which has heading as a class name
company_names = driver.find_elements_by_class_name('heading')
# to store all companies names from heading class name
names_list = []
while True:
try:
for name in company_names: # iterate each name in all div classes named as heading
text = name.text # get text data from those elements
names_list.append(text)
print(text)
# Click on next button to get data from next pages as well
driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="main-container"]/div[2]/div[4]/div[2]/div[44]/div[1]/ul/li[7]/a'))))
driver.find_element_by_xpath('//*[@id="main-container"]/div[2]/div[4]/div[2]/div[44]/div[1]/ul/li[7]/a').click()
except (TimeoutException, WebDriverException) as e:
print("Last page reached")
break
driver.quit()
# Store those data in excel sheet
df = pd.DataFrame(names_list)
writer = pd.ExcelWriter('companies_names.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='List')
writer.save()
【问题讨论】:
-
@VisheshMangla 我真的很想选择下一个按钮的类名或 id 之类的东西,但不幸的是它只包含 href 标记和说“下一个”的文本。
-
我明白我误解了一些东西,抱歉。
-
@VisheshMangla 非常感谢,这也很有帮助。现在我可以同时使用 BS4 和 Selenium 来报废了。
标签: python python-3.x selenium selenium-webdriver web-scraping