【问题标题】:Python BS4 - Write to JSON using a variable as key & valuePython BS4 - 使用变量作为键和值写入 JSON
【发布时间】:2021-05-10 19:24:12
【问题描述】:

所以我正在做一个小的网络抓取项目,我正在尝试遍历一个表。然后将表的左侧(tr)作为键,将表的右侧(td)作为该键的值放入 JSON 文件。它有点工作,这意味着它写入了正确的键/值。但它只写入表格中的最后一个单元格。

我尝试以几种不同的方式写入 JSON 文件,我在 google 上找到了一些关于它的帖子,但没有任何工作。

from bs4 import BeautifulSoup
import requests
import json


def writeToJSONFile(path, fileName, data):
    filePathNameWExt = './' + path + '/' + fileName + '.json'
    with open(filePathNameWExt, 'w') as fp:
        json.dump(data, fp, ensure_ascii=True)

path = './'
fileName = 'test'
data = {}

r = requests.get('https://www.newegg.com/msi-mpg-b550-gaming-carbon-wifi/p/N82E16813144322')

soup = BeautifulSoup(r.text, 'lxml')

tables = soup.findAll("table", class_='table-horizontal')
for x in range(len(tables)):
    for tr, td in zip(soup.findAll('table', class_='table-horizontal')[x].findAll('th'), soup.findAll('table', class_='table-horizontal')[x].findAll('td')):
        tr_item = tr.text
        td_item = td.text
        data["chassi"] = []
        data["chassi"].append({
            tr_item: td_item
        })

        writeToJSONFile(path, fileName, data)

我正在尝试遍历this 网站的specs

编辑: 这是我在 JSON 文件中得到的结果:

{ "chassi": [{ "Date First Available ": "June 15, 2020" }] }

【问题讨论】:

  • 为什么在你的循环中调用writeToJSONFile?把它移到你的循环之外。
  • 我给出答案请查收。它正在工作。您需要在for loop 之外定义您的字典。每次你的字典初始化并且你需要在for loop之外调用writeToJSONFile
  • 我还添加了如果没有数据存在则没有文件被创建。

标签: python json python-3.x beautifulsoup


【解决方案1】:
from bs4 import BeautifulSoup
import requests
import json


def writeToJSONFile(path, fileName, data):
    filePathNameWExt = './' + path + '/' + fileName + '.json'
    with open(filePathNameWExt, 'w') as fp:
        json.dump(data, fp, ensure_ascii=True)

path = './'
fileName = 'test'
data = {}

r = requests.get('https://www.newegg.com/msi-mpg-b550-gaming-carbon-wifi/p/N82E16813144322')

soup = BeautifulSoup(r.text, 'lxml')
data["chassi"] = []
tables = soup.findAll("table", class_='table-horizontal')
for x in range(len(tables)):    
    for tr, td in zip(soup.findAll('table', class_='table-horizontal')[x].findAll('th'), soup.findAll('table', class_='table-horizontal')[x].findAll('td')):
        tr_item = tr.text
        td_item = td.text
        
        data["chassi"].append({
            tr_item: td_item
        })

if len(data["chassi"]) > 0:
    writeToJSONFile(path, fileName, data)

【讨论】:

  • 有可能得到这样的东西吗? pastebin.com/HWzEtnqL - 可能值得一个新帖子本身,但我猜data["chassi"].append({}) 是它看起来像这样的原因:pastebin.com/iyRZDLie
  • @simonsjöö 是的,可以给我 10 分钟,我会为你做的。
  • 哦,太棒了。谢谢你:)
  • @simonsjöö 只需将 data["chassi"].append({tr_item: td_item}) 更改为 data["chassi"][tr_item] = td_item。和data["chassi"] = []data["chassi"] = {]。让我知道它是否有效?
  • 是的,解决了它。谢谢你:)
猜你喜欢
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
相关资源
最近更新 更多