簡體   English   中英

Scrapy Spider保存到csv

[英]Scrapy Spider save to csv

我正在嘗試抓取一個網站並保存信息,此刻我有兩個問題。

例如,當我使用硒單擊按鈕(在本例中為“加載更多結果”按鈕)時,它直到最后都沒有單擊,而且我似乎無法弄清楚原因。

另一個問題是它沒有保存到parse_article函數中的csv文件中。

這是我的代碼:

import scrapy
from selenium import webdriver
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from selenium.webdriver.common.by import By
import csv


class ProductSpider(scrapy.Spider):
    name = "Southwestern"
    allowed_domains = ['www.reuters.com/']
    start_urls = [
        'https://www.reuters.com/search/news?blob=National+Health+Investors%2c+Inc.']

    def __init__(self):
        self.driver = webdriver.Chrome()

    def parse(self, response):
        self.driver.get(response.url)

        while True:
            next = self.driver.find_element_by_class_name(
                "search-result-more-txt")
        #next = self.driver.find_element_by_xpath('//*[@id="content"]/section[2]/div/div[1]/div[4]/div/div[4]/div[1]')
        # maybe do it with this
        #button2 = driver.find_element_by_xpath("//*[contains(text(), 'Super')]")
            try:
                next.click()

            # get the data and write it to scrapy items
            except:
                break

        SET_SELECTOR = '.search-result-content'
        for articles in self.driver.find_elements(By.CSS_SELECTOR, SET_SELECTOR):
            item = {}
            # get the date
            item["date"] = articles.find_element_by_css_selector('h5').text
            # title
            item["title"] = articles.find_element_by_css_selector('h3 a').text

            item["link"] = articles.find_element_by_css_selector(
                'a').get_attribute('href')

            print(item["link"])

            yield scrapy.Request(url=item["link"], callback=self.parse_article, meta={'item': item})
        self.driver.close()

    def parse_article(self, response):
        item = response.meta['item']

        texts = response.xpath(
            "//div[contains(@class, 'StandardArticleBody')]//text()").extract()
        if "National Health Investors" in texts:
            item = response.meta['item']
            row = [item["date"], item["title"], item["link"]]
            with open('Websites.csv', 'w') as outcsv:
                writer = csv.writer(outcsv)
                writer.writerow(row)
  1. 單擊后嘗試稍等,以便加載數據。 我想有時候您的腳本會在顯示新數據和新按鈕之前搜索按鈕。

嘗試使用隱式等待或顯式等待:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element
# (or elements) not immediately available.
driver.implicitly_wait(implicit_wait)

# An explicit wait is code you define to wait for a certain condition to occur before proceeding further
# in the code.
wait = WebDriverWait(self.driver, <time in seconds>)
wait.until(EC.presence_of_element_located((By.XPATH, button_xpath)))
  1. “ w”僅用於寫入(具有相同名稱的現有文件將被刪除)。 嘗試使用“ a”(附加)參數。 雖然我建議使用管道: 鏈接

第一個問題似乎沒有出現。 也許可以幫助您。

還有一件事,嘗試在Scrapy關閉時關閉driver 也許可以幫助你。

第二個問題看起來您將要進行很多次open和編寫操作,但這並不好,因為您將覆蓋現有內容。 即使使用'a'標志,例如open(FILE_NAME, 'a')在Scrapy中也不是open(FILE_NAME, 'a')好習慣。

嘗試創建填充它的Item ,然后使用Pipelines機制將項目保存在CSV文件中。 這里的東西。

暫無
暫無

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

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