【问题标题】:store scraped data in format like csv, json, mysql/sql, txt from selenium scrip using python使用 python 从 selenium 脚本中以 csv、json、mysql/sql、txt 等格式存储抓取的数据
【发布时间】:2021-10-07 01:13:52
【问题描述】:

我正在从网站上抓取数据,我想将其存储为 JSON、excel、sqlite 或文本格式等格式,以便数据看起来井井有条且合理。请帮帮我。

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get('https://www.amazon.in/Skybags-Brat-Black-Casual-Backpack/dp/B08Z1HHHTD/ref=sr_1_2?dchild=1&keywords=skybags&qid=1627786382&sr=8-2')

product_title = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "productTitle"))).text

print(product_title)

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@data-hook='see-all-reviews-link-foot']"))).click()
    
while True:
    for item in WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[data-hook='review']"))):
        reviewer = item.find_element_by_css_selector("span.a-profile-name").text
        review = ' '.join([i.text.strip() for i in item.find_elements_by_xpath(".//span[@data-hook='review-body']")])
        print(reviewer,review)

    try:
        WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@data-hook='pagination-bar']//a[contains(@href,'/product-reviews/') and contains(text(),'Next page')]"))).click()
        WebDriverWait(driver, 10).until(EC.staleness_of(item))
    except Exception as e:
        break

driver.quit()

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/7528801/…
  • 这只是关于 CSV,我的偏好是 JSON 或 mysql
  • 您在问题中提到了 CSV。
  • 很抱歉有沟通障碍,但它也想知道 json 或 MySQL 与 csv

标签: python json excel selenium web-scraping


【解决方案1】:

将值 product_title、review 和 reviewer 存储在字典中,并使用 json 模块将其转换为 Json 格式。

您可以以这种格式存储数据,最后将列表转换为 JSON。

lst = [{"product_title": <title>, "reviews": [{"review": <review>, "reviewer": <reviewer>}, {"review": <review>, "reviewer": <reviewer>}....]
import json
json.dumps(lst)

将数据写入 JSON 文件

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(lst , f, ensure_ascii=False)

【讨论】:

  • 我将如何在 for 循环中使用它
  • 我们在这里为您提供帮助,而不是在您不付出任何努力的情况下解决您的整个问题。
  • 那么您希望将哪些数据存储为 JSON?
  • 对不起,我的朋友,我喜欢那些互相帮助的贡献者,你是其中之一 Ram,根据你的建议,我将它应用到我的代码及其工作中
  • 很高兴听到这个消息。 :)
猜你喜欢
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 2014-06-15
  • 1970-01-01
  • 2019-01-26
  • 2021-07-05
相关资源
最近更新 更多