【发布时间】:2019-11-21 03:15:56
【问题描述】:
我正在制作一个网站抓取工具,用于抓取网站并在网站中查找特定关键字,如果找到关键字,它将调用该网站为生产性网站或非生产性网站,然后将该信息导出到一个 json 文件中,所以我以后可以用c#得到它,但问题是json导出方法没有正确导出,我对pyhton和json都是新手。
我已经尝试了所有的所有语法,但似乎没有什么能像我想要的那样工作。
这是我的python代码
from bs4 import BeautifulSoup
import requests
import json
import os
import pandas as pd
import numpy as np
# this scraps the websites that i give it
def scrap_website():
pages = ['https://www.youtube.com/watch?v=tHI2NIaNrGk',
'https://aljazeera.com', 'https://www.svt.se']
for site in pages:
page = requests.get(site)
soup = BeautifulSoup(page.content, 'html.parser')
if 'Game' in soup.getText():
is_productive = False
json_map = {}
json_map["websiteLink"] = site
json_map["isProductive"] = is_productive
json_text = json.dumps(json_map)
else:
is_productive = True
json_map = {}
json_map["websiteLink"] = site
json_map["isProductive"] = is_productive
json_text = json.dumps(json_map)
data = []
data.append(json_text)
with open('data\\data.json', 'a') as json_file:
json.dump(data, json_file, indent=2, separators=(
", ", " "), sort_keys=True)
scrap_website()
这是我得到的 json 代码
[
"{\"websiteLink\": \"https://www.youtube.com/watch?v=tHI2NIaNrGk\", \"isProductive\": false}"
][
"{\"websiteLink\": \"https://aljazeera.com\", \"isProductive\": true}"
][
"{\"websiteLink\": \"https://www.svt.se\", \"isProductive\": true}"
]
【问题讨论】:
-
追加到数组,而不是字符串,然后序列化所有数据
-
也将
with语句从循环中移出,并在循环外创建list
标签: python json web-scraping beautifulsoup export