簡體   English   中英

在Python中使用Selenium進行網絡抓取

[英]Webscraping using Selenium in Python

我正在嘗試使用BeautifulSoup庫和Selenium包從Sunshine List網站( http://www.sunshinelist.ca/ )上抓取數據(以便處理網頁上的“下一步”按鈕)。 我知道有幾篇相關的文章,但是我無法確定應該在哪里以及如何明確要求駕駛員等待。

錯誤:StaleElementReferenceException:消息:stale的元素引用:元素不再附加到DOM或頁面已刷新

這是我編寫的代碼:

import numpy as np
import pandas as pd
import requests
import re
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

ffx_bin = FirefoxBinary(r'C:\Users\BhagatM\AppData\Local\Mozilla Firefox\firefox.exe')
ffx_caps = DesiredCapabilities.FIREFOX
ffx_caps['marionette'] = True
driver = webdriver.Firefox(capabilities=ffx_caps,firefox_binary=ffx_bin)
driver.get("http://www.sunshinelist.ca/")
driver.maximize_window()

tablewotags1=[]

while True:
    divs = driver.find_element_by_id('datatable-disclosures')
    divs1=divs.find_elements_by_tag_name('tbody')

    for d1 in divs1:
        div2=d1.find_elements_by_tag_name('tr')
        for d2 in div2:
            tablewotags1.append(d2.text)

    try:
        driver.find_element_by_link_text('Next →').click()
    except NoSuchElementException:
        break

year1=tablewotags1[0::10]
name1=tablewotags1[3::10]
position1=tablewotags1[4::10]
employer1=tablewotags1[1::10]  


df1=pd.DataFrame({'Year':year1,'Name':name1,'Position':position1,'Employer':employer1})
df1.to_csv('Sunshine List-1.csv', index=False)

我認為您只需要指向正確的firefox Binary。 另外,您正在使用哪個版本的Firefox? 看起來它是較新的版本之一,如果是這樣,應該這樣做。

ffx_bin = FirefoxBinary(r'pathtoyourfirefox')
ffx_caps = DesiredCapabilities.FIREFOX
ffx_caps['marionette'] = True
driver = webdriver.Firefox(capabilities=ffx_caps,firefox_binary=ffx_bin)

干杯

編輯:因此,為了回答您的新查詢,“為什么不寫CVS”,您應該這樣做:

import csv   # You are missing this import
ls_general_list = []

def csv_for_me(list_to_csv):
    with open(pathtocsv, 'a', newline='') as csvfile:
        sw = csv.writer(csvfile, delimeter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for line in list_to_csv:
            for data in line:
                sw.writerow(data)

然后將其替換為您的代碼df=pd.DataFrame({'Year':year,'Name':name,'Position':position,'Employer':employer})

為此, ls.general_list.append(('Year':year,'Name':name,'Position':position,'Employer':employer))

然后像這樣csv_for_me(ls_general_list)

如果滿意,請接受答案,而您現在擁有一個csv

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM